Anjith Paila
2 min readMar 2, 2020

--

Styling components in React using CSS modules

React has several ways to style components. In this tutorial we will look at one of those approaches: css modules. If you like writing css in separate files yet scoping it to particular components then this technique could help. For this tutorial let’s use create-react-app version 3.4.0. Historically we needed to eject create-react-app configuration to enable css modules but since CRA version 2.x.x, we wouldn’t need to that any more.

Now let’s create a react app with the following command: npx create-react-app cssmodules-demo. To demonstrate I have created a simple button on the landing page which will show/hide some articles. Our app, article components and their related css files should look like below:

We can see that css files are named like *.module.css. This is the convention we have to follow to enable modules feature. And we import css classes into react components using the syntax import classes from “./App.module.css. Here classes is kind of an object on which the relevant css classes are exposed as properties, for example, classes.button, classes.App, classes.Article etc. Also you can assign classes dynamically using javascript and write media queries using regular css syntax(see Article.module.css file).

The real benefit of css modules, however is scoping. Let’s start our project using the command npm start and inspect Show/Hide Articles button in developer console. We can see that some random string is added to our css class: this is added by webpack dynamically. If we have defined another button class in some other component then it will be imported using a different class name altogether — thanks to random string added- thus avoiding any global naming conflicts: cool isn’t it ?

If for some reason we would also like to define a global CSS class in a module file, we can prefix the selector with :global , for example, :global .button {}. And we can use such button using className=”button” syntax throughout our app and receive consistent styling.

Thanks for reading this article and let me know your feedback in comments. Happy learning!

--

--