Modular CSS with CSS Modules
Learn how to style React components using modular code while avoiding conflicts.
We'll cover the following
Importing and using CSS modules
CSS Modules are some sort of predecessor to CSS-in-JS and combine several properties from CSS and JavaScript modules. As the name already suggests, the CSS is found in their own importable modules, which, however, contain pure CSS and are tied to one particular component. If we were to develop a component to display a profile picture in a file called ProfileImage.js
, the CSS Modules approach often introduces another file with the name
ProfileImage.module.css
. When these CSS modules are imported, a cryptic class name is generated to ensure that the className
is only used in a single component. This aims to prevent class names from accidentally being used by two different components.
CSS Modules are only a concept and do not dictate a particular approach or implementation. The implementation is achieved by tools such as css-loader for Webpack.
It’s unnecessary to enforce the file ending of .module.css
(just regular .css
would also be okay), but it has become a convention in many well-known tools. Create React App also supports this convention out of the box without the need for further configuration by using the
previously mentioned css-loader in the background (implemented in Webpack).
In these CSS files, we can find regular and standardized CSS. It can then be imported into a JavaScript module with ease:
import css from './ProfileImage.module.css';
We’ve just entered new territory. The variable css
now contains an object with properties that relate to the class names in our CSS modules. If there is a CSS class in the CSS file that has the name image
, we can now access the property image
on the CSS object. The resulting value in the rendered markup is a unique string such as ProfileImage_image_2cvf73
.
We can pass these generated class names to our components like this:
<img src={props.imageUrl} className={css.image} />
This code would result in the following rendered markup:
<img src="..." className="ProfileImage_image_2cvf73" />
Let’s see this in action.
Get hands-on with 1200+ tech skills courses.