Search⌘ K

CSS Modules in React

Explore how to apply CSS Modules in React to achieve scoped and maintainable styles. Learn to rename CSS files, import styles as JavaScript objects, use multiple classes with template literals, and consider alternatives like the classnames library for dynamic styling. Understand the advantages of CSS Modules compared to traditional CSS, including improved error detection during development.

We'll cover the following...

CSS Modules are an advanced CSS-in-CSS approach. The CSS file stays the same, where you could apply CSS extensions like Sass, but its use in React components changes. To enable CSS modules in create-react-app, rename the src/App.css file to src/App.module.css. This action is performed in the command line from your project’s directory:

Shell
mv src/App.css src/App.module.css

Note: This command is to be executed when you run this on your local machine. You can see the live execution of code at the end of this lesson.

In the renamed src/App.module.css, start with the first CSS class definitions, as before:

Scss
.container {
height: 100vw;
padding: 20px;
background: #83a4d4; /* fallback for old browsers */
background: linear-gradient(to left, #b6fbff, #83a4d4);
color: #171212;
}
.headlinePrimary {
font-size: 48px;
font-weight: 300;
letter-spacing: 2px;
}

Import the ...