Member-only story

Using CSS Modules In React App

Shuai Li
3 min readAug 22, 2021

--

This article is part of the Robot Mall series

In this section, let’s talk about how to import a CSS file modularly in React.

If we want to include a CSS file in a React component, we only need to use the import syntax:

import './index.css';

Later when we are packaging the project, webpack will package the corresponding CSS style and JavaScript code together.

But this way of importing CSS styles is actually a global import, which means that the CSS styles defined in index.css will become common styles for all components of the entire page.

In large projects, this approach is very easy to cause naming conflicts. For example, we imported A.css in component A, and the style .btn{color: red} was defined in A.css; at the same time, we imported B.css in component B, and .btn{color: blue} was defined in B.css. At this time, if we package this project directly, there will be a naming conflict.

One of React’s missions is to allow us to develop modularity. In order to make our components truly modular, we need to make modular import to CSS styles so that a CSS style only takes effect in a specific component.

So how to modularize import CSS? In fact, it is very simple to import CSS modularly, which is 3 steps:

  • Modify the suffix of the CSS file to .module.css
  • Use import styles from 'App.module.css’ to import CSS styles

--

--

Shuai Li
Shuai Li

Written by Shuai Li

An enthusiastic game player of Earth Online.

No responses yet