React ยท Chapter 25 of 42
CSS Modules
CSS Modules let you write regular CSS files where class names are automatically scoped locally to the component that imports them, avoiding global naming collisions.
A file named `Button.module.css` is processed so each class becomes a unique, generated identifier under the hood.
Using CSS Modules
Name your file `Component.module.css`, import it as an object, then reference classes via `styles.className`.
Local scoping benefit
Because class names are hashed to be unique, you can reuse simple names like `.title` or `.container` across many files without conflicts.
Example 1 (jsx)
// Button.module.css
// .primary { background: blue; color: white; }
import styles from "./Button.module.css";
function Button() {
return <button className={styles.primary}>Click</button>;
}Output
<button class="Button_primary__a1b2c">Click</button>styles.primary maps to a uniquely generated class name.
Key points
- CSS Modules scope class names locally per component file.
- File names end in `.module.css`.
- Import styles as an object and access classes as properties.
- Prevents global class name collisions in large codebases.
๐ก Note: Vite and most modern React toolchains support CSS Modules out of the box, no extra config needed.
