3
votes

What would be the best way to combine (custom) CSS modules with Bootstrap within a React component? I'm using the Bootstrap CDN to fetch the styles and use them inside a component. How do I apply custom styles to (for example) .nav-link using a CSS module connected to the component? In other words, how do I override Bootstrap's default styling? Suppose the following is my code:

Component

import React from "react";
import styles from "./Navbar.module.css";

function Navbar() {
   return (
      <nav className="navbar navbar-expand-lg">
         <div className="collapse navbar-collapse" id="navbarNav">
            <ul className="navbar-nav ml-auto">
               <li className="nav-item">
                  <a className="nav-link" href="#">Home</a>
               </li>
               <li className="nav-item">
                  <a className="nav-link" href="#">About</a>
               </li>
            </ul>
         </div>
      </nav>
   );
}

export default Navbar;

CSS

.Navbar {
   background-color: green;
}



Knowing the import of the css module allows me to use styles.Navbar as a classname, I came up with this in order to make the background color of the navbar green.

<nav className={`navbar navbar-expand-lg ${styles.Navbar}`}>

However, I am unable to catch any bootstrap related classes inside the CSS module. The goal is to get something like this, where I'm able to override Bootstrap within the css module.

.Navbar {
   background-color: green;
}
.Navbar .nav-link {
   color: red;
}
2
Why don't just overwrite bootstrap classes ? .navbar { background-color: green !important }johannchopin

2 Answers

0
votes

My opinion is you should generally avoid using descendant selector .class1 .class2 when it comes to css modules and React component approach. I would rather simply create a .navigationLink class and apply it directly to <a> </a> element. Then you could make it a separate <NavigationLink/> component for reusability.

Another approach is to use Bootstrap theming for changing something like link color globally:

https://getbootstrap.com/docs/4.1/getting-started/theming/ https://github.com/twbs/bootstrap-sass/blob/master/assets/stylesheets/bootstrap/_variables.scss#L35

0
votes

The component that imports bootstrap your-component.js for example, looks like this:

/* Bootstrap */
import "bootswatch/dist/cosmo/bootstrap.min.css";  

/* Custom Styling */
import './your-override.css';

You can easily override by importing a css file after importing the bootstrap.css, if you add a style in this file (your-override.css) with the same class name or id etc. as bootstrap has it will override.

DO NOT USE !important. It's really bad practice.