Loading

Quipoin Menu

Learn • Practice • Grow

react / CSS Modules in React
tutorial

CSS Modules in React

In traditional CSS, all styles are global. This can lead to conflicts, especially in large applications where different components might accidentally use the same class names. **CSS Modules** solve this problem by locally scoping class names by default.

What are CSS Modules?

CSS Modules is a CSS file in which all class and animation names are scoped locally by default. When you import a CSS Module into a React component, the class names are transformed into unique identifiers, ensuring they don't clash with other classes.

Think of CSS Modules as giving each component its own private CSS namespace. You can write simple class names without worrying about conflicts.

How to Use CSS Modules in React

Create a CSS file with the extension `.module.css`. Then import it into your component as an object, and use the class names as properties.
<!-- Button.module.css -->
.btn {
  padding: 10px 20px;
  background: blue;
  color: white;
  border: none;
  border-radius: 4px;
}

.btnPrimary {
  background: green;
}

<!-- Button.js -->
import React from 'react';
import styles from './Button.module.css';

function Button({ primary, children }) {
  const className = primary ? `${styles.btn} ${styles.btnPrimary}` : styles.btn;
  return <button className={className}>{children}</button>;
}

export default Button;

How CSS Modules Work

During build, CSS Modules generate unique class names like `Button_btn_1a2b3c`. This ensures that styles are scoped to the component and don't leak.

Advantages of CSS Modules
  • No naming conflicts class names are locally scoped.
  • Explicit dependencies you import only the CSS you need.
  • Works with regular CSS syntax no learning curve.
  • Can be combined with preprocessors like Sass.

Two Minute Drill

  • CSS Modules locally scope class names to prevent conflicts.
  • Name your CSS files with `.module.css` extension.
  • Import the module as an object and use styles.className.
  • The build process generates unique class names automatically.
  • Ideal for component-based styling without global pollution.

Need more clarification?

Drop us an email at career@quipoinfotech.com