CSS Modules In React

Ahmed EssamAhmed Essam
2 min read

In this blog, we will be introducing CSS modules that will help us in styling React components. As we know, to import a CSS file in react we will do the following:

import './Compoenent.css'

The problem is that when working on big projects, you don't want styles to overwrite others which is hard to configure if you are a team working on the project.

Here is where CSS modules stars by scoping styles.

Attention: This will only work on React projects which are installed with create-react-app

The way to use it is simple. First, we will change the CSS file name to Component.module.css, then we will import it

import styles from './Component.module.css'

The way this complies is that React turns the selectors to keys of objects that hold the styles, so now if you want to use the styles on a specific element we will do the following, but before that let's assume that we have the following selector in the CSS file

// CSS file

form {
  padding: 10px;
}

form.invalid {
  background: red;
}

input {
  border: none'
}
// Component File

import styles from './Component.module.css'

return (
// assume that you have a valid boolean from state
<form className={`${styles.form} ${!valid && styles.invalid}`}> 
   <input className={styles.input}>
 </form>
)

Be aware that the selector object comes with all media queries that are attached to this selector and also comes with the pseudo classes/elements

As an alternative to CSS modules, you can use styled component which will let you implement your code in the component JS file. You can visit styled-component

1
Subscribe to my newsletter

Read articles from Ahmed Essam directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ahmed Essam
Ahmed Essam