Tahir Ahmed
Tahir Ahmed

Tahir Ahmed

How to use CSS Modules in React

How to use CSS Modules in React

Tahir Ahmed's photo
Tahir Ahmed
·Mar 15, 2022·

2 min read

Table of contents

  • Problem with CSS
  • Why CSS Modules?
  • How to use CSS Modules

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.

Problem with CSS

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.

Why CSS Modules?

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.

How to use CSS Modules

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>
    )
}

Using more than one CSS class for a component

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.

 
Share this