How to use CSS Modules in React

Search for a command to run...

No comments yet. Be the first to comment.
Developer tools provided by browsers are an invaluable asset for web developers. They enable us to quickly diagnose issues, edit HTML in real-time, and iterate on our web applications more efficiently. In this article, we will explore one such powerf...

call(), apply() and bind() and creating our own implementations of these methods

for react projects created using custom webpack configurations

I am currently interviewing for Frontend Developer roles and I failed one of the interviews because I was not good at Object Oriented Javascript. Writing this article to serve me as a goto article for any interview preparation in future and for other...

Hello everyone,
Hope you are doing well.
This will be a very small article where I will talk about how to get started with CSS Modules in React Apps. Without wasting much time lets get into it.
The CSS defintions in React are global scoped - meaning two or more classes with same name conflict with each other. Handling CSS becomes messy as the size of the project grows.
A CSS module is .css file where classes behave like Javascript variables. CSS Modules localize the class names and allow the users to use the same class names across the project.
They automatically create unique className for the CSS class using the format [filename]\_[classname]\_\_[hash] and scope the CSS classes locally.
For more information, read the docs.
Using CSS modules is very easy. We need to name our files in the format *.module.css*. It is considered as a good practice to name the css module file with the same name as the component name in which it will be used.
|__Components
|__Homepage
|__Homepage.js
|__Homepage.module.css
// Define the classes normally as we define in normal css files
.container {
display:flex;
flex-direction: column;
width: min(90vw - 2em, 80em);
margin: 0 auto;
}
While using these classes we need to use the format {styles.container} where styles is the name which we are using to import and container is the css classname defined in our .module.css file. They are imported and used as shown below.
import styles from "./Homepage.module.css";
export default function Homepage(props) {
return (
<div className={styles.container}>....content</div>
)
}
It is not likely that all our css is written in one single class. We might have normal CSS classes coming from component libraries and other css module classes too. They can be used as below
<div
className={`${styles.classone} ${styles.classtwo} flex flex-column`}>
content
</div>
classone and classtwo are classes defined in *.module.css file and flex and flex-column are normal css classes defined in component libraries.
Here is a link to Code Sandbox where I have created two components and styled them using CSS modules.
That's all for this article.
Thanks for reading.