Using CSS modules in ReactJS

Johnny Lai
2 min readOct 2, 2020

Problem

As everything finally will be import to App.js, we have to define unique style class name for different components. By default, all CSS class defined in React available globally. You can define all CSS class with unique name, but normally we have several dozen of class, in large project, maybe more than one hundred, it is very waste time to check whether that name is unique or not when you going to define a new CSS class.

Objective

Limit the styles to certain components instead of the whole applications

Result

The scope of that CSS class will limit to those imported that CSS file, that means you’re free to use same naming for CSS class by import different CSS files, we can use same naming for style class in different components. In the background React will automatically append random string to those style class when we import to App.js

Part 1. react-scripts: 2.0.0 or above

No configuration required, but css file must be ended with “.module.css”

Examples

ComponentA/component.js

import React from 'react';
import styles from './component.module.css';
const ComponentA = props => (
<div>
<h3>
Component A
</h3>
<button className={styles.button}>
buttonA
</button>
</div>
);
export default ComponentA;

ComponentA/component.module.css

.button {
background-color: green;
}

ComponentB/component.js

import React from 'react';
import styled from './component.module.css';
const ComponentB = props => (
<div>
<h3>
Component B
</h3>
<button className={styled.button}>
buttonB
</button>
</div>
);
export default ComponentB;

ComponentB/component.module.css

.button {
background-color: blueviolet;
}

App.js

import React from 'react';
import logo from './logo.svg';
import './App.css';
import ButtonA from './ComponentA/component';
import ButtonB from './ComponentB/component';
export default () => (
<div>
<ButtonA/>
<ButtonB/>
<h3>Button in App.js</h3>
<button className='button'>Button</button>
</div>
);

App.css

.button {
background-color: yellow;
}
The CSS class for component A and component B appended with random string as they applied CSS module by the naming convention component.module.css

Done~!

Part 2. react-scripts: 1.x

Access to the configuration files

npm run eject

Insert these 2 lines to webpack.config.dev.js and webpack.config.prod.js

test: /\.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
modules: true,
localIdentName: '[name]__[local]__[hash:base64:5]'

},
},

Restart the server

Done~!

--

--