DEV Community

Cover image for CSS Modules in react?
Narasimma Radhakrishnan
Narasimma Radhakrishnan

Posted on

CSS Modules in react?

In React, CSS Modules are CSS files where class names are scoped locally by default.
The CSS file have to have the .module.css extension and can be used by importing it into your React file(s).

Creating a CSS Module

Let's create a CSS module called Button.module.css, where we style some buttons.

Create a file named Button.module.css, and insert some styles in it:

Button.module.css

.mybutton {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
Enter fullscreen mode Exit fullscreen mode

Using a CSS Module

import styles from './Button.module.css';

function App() {
  return (
    <div>
      <button className={styles.mybutton}>
        My Button
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

We import the styles object from the CSS Module
We use styles.mybutton to access the mybutton class
The actual class name of the button will be unique (e.g., _mybutton_q1obu_1)

Top comments (0)