CSS Modules helps you create independent and customized cascading style sheets for any .js file rendering HTML in your React application.
If you are beginning to learn React and find yourself creating small projects you won't have any issue getting all your CSS code from a main file:
Here we have a simple React project structure for a simple application which doesn't require a big amount of styling, given the fact that is only composed by
and user_list.js
user_details.js
containers and a main App.js
component the best and simpler way to import the CSS code to style it would be from just the style.css
file.So... what happens when your application gets bigger and you need to start styling a considerable amount of components? You will realize managing multiple CSS selectors from several files into just one
style.css
is not the ideal solution. You will run into problems managing unique ids, classes and tag elements for each individual file so they dont end up overriding each other, here's where CSS Modules enter the game:Modular CSS gives you the advantage of importing CSS to each individual React component by passing the '' object with the mapped properties of its own CSS file.styles
Let's take a look at the Book component:
As you can see in the above example, all we need to do is a simple import:
import styles from './ComponentName.module.css';
Then, we can access every property with the styles object :
<div id={styles.mainContainer}>
<h1 className={styles.blueHeader}>Hello World</h1>
</div>
*It's suggested to use camelCase for CSS selectors in order to avoid unexpected behaviors.
Composing from other CSS modules:
It's also possible to import another CSS module to compose mixed properties:
.bigGreenBox {
composes: bigBox from "./style.css";
background-color: green;
}
Conclusions
Links
If you made it this far i hope this article helped you in one way or another, thanks for reading!