Using CSS modules in React
A case for CSS Modules and how to implement them into your React App
If you are relatively new to CSS, you may or may not have encountered the significant problem that occurs as an application’s style expands— since CSS rules follow global scope, two or more classes of the same name will collide. Handling multiple stylesheets and keeping track of naming conventions in CSS files can get burdensome, and if you aren’t careful enough, you are bound to encounter some conflicts from identical class names.
CSS Modules can solve these errors likely to appear, especially as your application grows. They ultimately allow us to use the same class name in multiple files without selector and rule errors by scoping class names locally by default.
A CSS Module is simply a .css
file, where classes act similarly to local variables in Javascript. It is a tool that makes every class unique by including a hash in their name.
Creating a CSS Module
If you are using create-react-app
, making CSS Module for a component is relatively easy. Follow the typical naming convention for a css file, but insert module
before .css
, like so: [name].module.css
To see an example, here is my Task.module.css
file within a simple to-do app:
If I have another box
class in a different component that has a different color, those rules will not collide since modules apply local scope.
To import a CSS Module into the corresponding component, import the css modules stylesheet as styles
or [name]Styles
:
In JSX, use the defined CSS class as a className prop like so:
From here, you can add as many other CSS modules you’d like, just remember to import each as a different name.
With CSS Modules, you can create portable, reusable CSS files and no longer need to be concerned with selector name collisions or rules impacting another component’s styles.
Often when faced with the styling decision for React apps, developers are torn between using CSS Modules or a CSS-in-JS (tool for abstracting the CSS to the component level) library like styled-components, Emotion, or styled-jsx. As CSS-in-JS libraries are becoming more widely used and mainstream for describing styles declaratively, I’ve noticed that many still believe CSS Modules are the way to go, especially for their modular and reusable qualities that make the styling experience that much more seamless.