In this tutorial, we will explore how we can use CSS Modules in React to make maintaining our CSS files way easier and more modular.

When building React applications (or any application actually), we need it to look great. For web applications, the standard beautification language is called CSS. Since the age of the dinosaurs, properly structuring CSS styles and arranging them has always been a problem.

In small apps, this is not really a problem, but with applications of larger structure, things are bound to get real hazy. With CSS Modules we can modularize things in React and add some structure to the flow.

Let’s have a real look at the problems we are trying to solve.

CSS at scale

CSS has always been easy and flexible, but then this really cool technology doesn’t really lend itself to scalability. With large projects that have extended sections and features, it becomes a real menace to deal with.

At scale these problems become real (scale here referring to a codebase with many developers working on it), but then there are a couple of problems that we have to take into account and make sure we understand before we attempt to solve them.

Some of the problems are:

1. Global ~~warming~~ namespaces.

2. Dead code elimination.

3. Dependencies.

4. Conditionals.

Global namespaces

CSS is a language of globals. In most languages, global variables are considered bad and taking into account we have CSS styles mostly specific to our components, it’s obvious that globals are bad (there are cases when using global CSS is okay though).

Global CSS can easily rewrite styling in other classes. A change in the style in one class can ultimately and silently change the UI on multiple components. Generally, no one wants that to happen when they develop apps.

Dead code elimination

Most times while building apps, we have styling that is redundant or no longer in use. Although they can be small at first, over time it builds up and we have rogue and unused CSS everywhere and it can cause unnecessarily large file sizes.

With CSS modules, we get to only import styles we use. therefore reducing redundancy and the increase in our ability to spot CSS that is not being used.

Dependencies

Working with dependencies in CSS is hazy. Most of the time we are used to just including the entire script directly into the page whether they are being used or not.

Conditionals

Sometimes you need your CSS class to style in a certain way in one section and in a different way in another section. In this case, it is usually better to have the CSS class variable modifiable in the component.

Modular CSS solves each of these problems in a clean structured manner by having our components import only the classes they actually use therefore getting rid of redundancy. This in itself also solves the problems of global namespaces.

Working with CSS modules

When working with modular CSS in React, we can work in a few ways:

– Using CSS as JavaScript Objects.

– Using CSS Modules.

We will focus on CSS modules but shine a little light on the former.

CSS as JavaScript objects

Writing CSS as JavaScript objects are easier in the context of React as it ensures you do not have to stray from JavaScript to write CSS. In JavaScript, CSS classes look similar and CSS classes are named in camel cased versions of the property name.

CSS written as JavaScript objects can be leveraged directly in React components by using the style attribute on components.

Here is an example:

// lets have some CSS in js: style.css.js const button = { backgroundColor: '#202020', padding: '12px', borderRadius: '2px', width: '100%' } export default { button } //importing and using in a JSX import styles from './style.css.js' const button = () => { return <button style={styles.button}>Vanity Button</button> }

The code above is a clear example of using CSS as a JavaScript object and it allows us to have styling that is unique to that element.

Another thing you can do when defining the CSS as a JavaScript object is use variables as the values for the style property. In this way it can change depending on some conditions:

// lets have some CSS in JS: style.css.js var variables = { backgroundColor: '#202020' } var button = { backgroundColor: variables.backgroundColor, padding: '12px', borderRadius: '2px', width: '100%' } export default { button }; // importing and using in a JSX import styles from './style.css.js' const button = () => { return <button style={styles.button}>Vanity Button</div> }

One of the major wins with CSS as JavaScript objects is it requires no setup to get it working. Since it’s plain JavaScript you are good to go. Although CSS in JavaScript is extensible it does have its limitations in various areas.

CSS modules

CSS modules are not very different from the method above. However, with CSS modules, we can write our usual CSS code and import that into our component.

Here is an example:

// lets have some CSS in JS: style.css .button { background-color: #202020; padding: 12px; border-radius: 2px; width: 100px; } // Importing and using in a jsx import styles from './style.css' import React from 'react'; export default class Button extends React.Component { render(){ return ( <button className={styles.button}>Vanity Button</button> ) } }

In the code above, you can see that the CSS is actual CSS and not a JavaScript object. However, this in itself will not work and we will need to configure our loader to make it work.

Setting up for CSS modules

Most of the configuration for our application to work with CSS modules will be done in the webpack configuration file. So assuming you have set up a React application using create-react-app , you will need to take control of the configuration of your app using the eject command:

$ yarn eject

? With normal apps not created using create-react-app you can configure Webpack in a similar way as shown in this article.

After ejecting, we can update our webpack.config.dev.js file to reflect our setup for CSS modules. In the webpack configuration file, replace the content below:

{ loader: require.resolve('css-loader'), options: { importLoaders: 1, }, },

with the following configuration:

{ loader: require.resolve('css-loader'), options: { importLoaders: 1, modules: true, localIdentName: "[name]__[local]___[hash:base64:5]" }, }

With the change, we can now use CSS modules in our project. We have also set up hashing to properly generate names for the classes being used in the modules.

? You can use a shorthand to specify the same loader like so: loader: 'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]``'

If you are not using create-react-app , adding the required options and setting up the extractTextPlugin will be the way to set up CSS Modules:

import ExtractTextPlugin from 'extract-text-webpack-plugin' module.exports = { .... plugins: [ .... new ExtractTextPlugin('style.css') ] }

Now we can reconfigure our loader to find our CSS files and bundle them together:

loader: ExtractTextPlugin.extract( 'style-loader', combineLoaders([ { loader: 'css-loader', query: { modules: true, localIdentName: '[name]__[local]___[hash:base64:5]' } } ]) )

Taking things a step further

Let’s take things a step further using the react-css-module . You can install this via the npm registry:

$ yarn add react-css-modules

With react-css-modules we can have our code like this now:

// lets have some CSS: style.css .button{ background-color: #202020; padding: 12px; border-radius: 2px; width: 100px; } //importing and using in a jsx import styles from './style.css' import React from 'react'; import CssModules from 'react-css-modules'; class Button extends React.Component{ render(){ return ( <button styleName='button'>Vanity Button</button> ); } } export default CssModules(Button, styles);

? Using the react-css-modules , we don’t have to specify the style as an object, but rather we can specify it as a class name and have the style object added to the entire component using the CssModule function.

Explaining an example usage of CSS modules

To demonstrate how CSS Modules can be used we will be creating a To-do application (yes I know, again). The demo implements CSS Modules, with every component implementing its own style. You can download the demo on GitHub.

In the config/webpack.config.dev,js file and the config/webpack.config.prod.js file, we update the CSS loaders configurations to use the CSS modules:

use: [ ... { loader: require.resolve('css-loader'), options: { importLoaders: 1, modules: true, localIdentName: "[name]__[local]___[hash:base64:5]" }, } ... ],

Next, we installed the react-css-modules package by running the command below in our terminal:

$ npm install react-css-modules

Now we can create a CSS file called todoItem.css and paste in the following:

.TodoItem{ width: 100%; min-height: 30px; padding:12px; border-bottom: 1px solid #ededed; } .removeOp{ content: "/f00d"; color: red }

And then paste this in our JavaScript file:

import React from 'react' import propTypes from 'prop-types' import CssModules from 'react-css-modules' import s from './todoitem.css' class TodoItem extends React.Component{ render(){ return ( <div styleName="TodoItem"> {this.props.title} <span styleName="removeOp" onClick={()=>this.props.remove(this.props.id)}>click to remove</span> </div> ) } } TodoItem.propTypes = { title: propTypes.string.isRequired, id: propTypes.number.isRequired, remove: propTypes.func.isRquired } export default CssModules(TodoItem, s)

Above you see we can easily use the CssModules package in exporting our components while hooking them to the style implementation. We can use the styleName property to specify the specific styles we want in the stylesheet.

Conclusion

We have considered how you can use CssModules to change the way you work with styles in your React application. You can combine this method with a CSS preprocessor like Sass or Less.

We also learned about the methods of including CSS in our React components. While both methods share certain advantages, the implementation differs: one is actual CSS living in CSS files wired with JS modules using imports and hashed class names at build time, the other is actual JS from the start and is composed and attached to elements in the form of inline styles at execution time.

If you have any questions and feedback, please leave them as a comment below.