How to use CSS Modules in React?

 by Robin Wieruch
 - Edit this Post
react css modules

This tutorial is part 2 of 2 in the series.

CSS Modules are one of the most popular ways for styling React components. Whether you are using only CSS or a more advanced pre-processor like SASS, it doesn't matter for CSS Modules: You can write all these styles in your style sheet files next to your React components.

Since we are building up on top of a custom React + Webpack application, it needs some set up from our side before we can start using CSS Modules in React. I want to thank Arpit Batra for showing use how it works.

Note: If you are using create-react-app, just follow this Create React App with CSS Modules tutorial. It comes with CSS Modules out of the box. If you are using your custom React + Webpack setup, maybe from a previous tutorial of mine, keep reading for setting up CSS Modules in your custom React project.

First, we need some more loaders for Webpack. These loaders enable Webpack to bundle CSS files as well:

npm install css-loader style-loader --save-dev

And second, in your webpack.config.js file, add the new loaders for interpreting CSS files:

module.exports = {
...
module: {
rules: [
...
{
test: /\.css$/i,
exclude: /node_modules/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
},
},
],
},
],
},
...
};

That's already it for the CSS Modules setup in Webpack. Next, you can define your first CSS file. Let's name it src/style.css:

.title {
color: blueviolet;
}

Then you can import the CSS file in one of your React components. Afterward, you are already able to use the CSS class defined in the CSS file in your React component. Just import it and use its defined CSS class as className prop in your React component.

import React from 'react';
import styles from './style.css';
const App = ({ title }) => (
<div className={styles.title}>{title}</div>
);
export default App;

From here you are prepared to add more CSS files next to your React components. Normally one would use one style file for each React component. In this CSS file, you are free to add as many CSS classes as you need to style your React component. Simply import the styles from the CSS file and use them as shown before in your React component.

Keep reading 

The article is a short how to use CSS Modules in your create-react-app application . It shows you how to setup CSS Modules, but also how to use them in your components. After you have setup your…

So much has been said about the appropriate way to style modern web apps. There's the general and oldest method of styling at document level - creating a style.css file and linking to it in the HTML…

The Road to React

Learn React by building real world applications. No setup configuration. No tooling. Plain React in 200+ pages of learning material. Learn React like 50.000+ readers.

Get it on Amazon.