A quick overview of what is CSS Modules, how it works, how it’s used together with React, plus some useful tips
What is CSS Modules?
A CSS Modules is a CSS file in which all class names and animation names are scoped locally by default.
How does CSS Modules work?
- CSS styles: compiled CSS with modified class names.
Also, create-react-app supports CSS Modules out of box.
See, how original class name
.container was renamed to a
.styles_container_g2x5j , in order to scope CSS locally and avoid class name conflicts.
.styles_container_g2x5jis just an example.
It’s possible to configure CSS modules compiler class name generation pattern/function.
Using with React
Using CSS Modules in React is really straight forward.
Simplifying things with “classnames”
Probably, you’ve already noticed that multiple and conditional class names don’t look nice, and seem to a bit overcomplicated.
One way to solve this is to create some utility functions to work with
However, there’s already such npm package called classnames.
Simplifying things further with “babel-plugin-react-css-modules”
So far when using
classnames npm package code looks much better.
However, it’s still a bit different from what just regular HTML/CSS classes look like when we just write
<div class="foo bar">...</div> .
There is babel-plugin-react-css-modules that brings back that functionality into CSS Modules. With this plugin enabled, we can provide original class names to a special
styleName attribute and the plugin replaces them with modified class names during build time.
classNameusing compile time CSS module resolution.
CSS Modules and React plays very well and, most importantly, solves the issue of having global styles and class name overlapping, while keeping CSS and JS separate.
However, there is another approach for creating locally scoped styles, which is called CSS in JS. There are plenty of implementations/libraries of CSS in JS such as styled-components, emotion, JSS, etc. The choice between CSS Modules and CSS in JS is a matter of preference of a developer or team, and of course, consistency within a project.
We are also always interested in helping to promote quality content. If you have an article that you would like to submit to any of our publications, send us an email at email@example.com with your Medium username and we will get you added as a writer. Also, let us know which publication/s you want to be added to.