How to style React with CSS Modules

My favorite way to style React components is CSS Modules. It works like vanilla CSS, but with a welcome twist. Let’s say you have a component called BrightDiv with a corresponding JS and CSS file:

BrightDiv.js
import React from 'react'
import styles from './BrightDiv.css'

const BrightDiv = () =>
  <div className={styles.yellow} />

On Line 2, you import styles. On the last line, you set the div’s className to styles.yellow to reference the class straight out of your CSS:

BrightDiv.css
.yellow {
  background: #ffff00;
}

When your application compiles, CSS Modules will automatically transform {styles.yellow} and .yellow into a unique classname such as yellow_74hd_6h38. This transformation ensures that other components, although they may be using another {styles.yellow}, will not conflict with BrightDiv’s styling.

Main Benefits

Think “plain English CSS that never causes conflicts”:

.enabled  { color: green; }
.disabled { color: red; }

Global Classes

Want to use utility classes or frameworks without importing them into every file? Use :global(xxx) to create globally-scoped classes.

:global(.darkBackground) {
  background: #222;
}

You can now use <div className="darkBackground"> (just a string, not a JavaScript object) to reference that class. Keep in mind that these classes won’t be transformed by CSS Modules, so there may be style conflicts.

Although I said “conflicts” in the last line, I don’t believe that using global classes is a bad practice. If you have utility classes or a simple grid system, I recommend globalizing them to avoid duplication.

Structure

I like to create a CSS file for each component, and I stay away from inline styles as much as possible.

components/
├── Button/
│   ├── Button.js
│   ├── Button.css
│   └── index.js
├── Carousel/
│   ├── Carousel.js
│   ├── Carousel.css
│   └── index.js
└── Grid/
    ├── Grid.js
    ├── Grid.css
    └── index.js

Final Word

So far, I’ve been happiest when running a few globally-scoped styles (mainly a lightweight grid system and a few utility classes) and handing it to CSS Modules to take care of the rest.