CSS Modules StyleSheet in React

3 min read  •  09 Jan 2022
view-count

What are CSS Modules?

CSS Modules are nothing but css files in which all the styles are scoped locally by default.

If we use normal css, the styles (class names, animation) are scoped globally. But with css modules we can have same class name in different files.


Let's check it in action with example of using normal css and css modules in React-


Using Normal CSS

Suppose we have two different CSS files (for two different things) which have a same class name. And, we want to use that same class name from both css files in a React Component. Then while assigning className, we dont have a way to tell from which css file we should pick the class name.


In the example below, we have an App component which has a blog and subscribe form. For both, blog and subscribe form we have a class name (wrapper) defined in respective css files. But we can see that the styles of the file which is imported last is preferred, and we cannot chose from where it should take the class name.

App.js
import "./blog.css";
import "./subscribe.css";

export default function App() {
  return (
    <>
      <article className="wrapper">
        Consider this as a blog space.
        <p>This is paragraph 1</p>
        <p>This is paragraph 2</p>
        <p>This is paragraph 3</p>
      </article>
      <section className="wrapper">
        <h1>Subscribe here</h1>
        <input placeholder="Email" />
        <button>Submit</button>
      </section>
    </>
  );
}
blog.css
.wrapper {
  background-color: yellow;
}
subscribe.css
.wrapper {
  background-color: brown;
}
Output

normal-css-output

To overcome this, we can use CSS as modules (CSS Modules)


Using CSS Modules

To use CSS Modules, we need to rename our css files from .css to .module.css, so that the bundler can identify it. Or else, we can set the css-loader option modules as true in webpack configuration. Check more about it here.

Here's how we can use CSS Modules in React-

App.js
import blogStyles from "./blog.module.css";
import subscribeStyles from "./subscribe.module.css";

export default function App() {
  return (
    <>
      <article className={blogStyles.wrapper}>
        Consider this as a blog space.
        <p>This is paragraph 1</p>
        <p>This is paragraph 2</p>
        <p>This is paragraph 3</p>
      </article>
      <section className={subscribeStyles.wrapper}>
        <h1>Subscribe here</h1>
        <input placeholder="Email" />
        <button>Submit</button>
      </section>
    </>
  );
}
blog.module.css
.wrapper {
  background-color: yellow;
}
subscribe.module.css
.wrapper {
  background-color: brown;
}
Output

css-modules-output

That's how we can take advantage of CSS Modules in our React app to achieve modularity among components styling.