π¨ CSS Modules in React
CSS Modules allow you to write traditional CSS scoped to individual components β preventing class name conflicts and global pollution.
π¦ 1. File Naming
Name your stylesheet as ComponentName.module.css
to enable CSS Modules.
// Button.module.css
.button {
background-color: #1d4ed8;
color: white;
padding: 8px 16px;
border-radius: 6px;
font-weight: bold;
}
βοΈ 2. Import & Use Styles
Import the styles as an object and reference classes as properties:
import styles from './Button.module.css';
function Button() {
return <button className={styles.button}>Click Me</button>;
}
π 3. Scoped Styling
- CSS Modules generate unique class names at build time.
- This ensures styles are applied only to the intended component.
- No global style conflicts β safe for large apps!
π§ͺ 4. Conditional Classes
Use template literals or libraries like clsx
for conditionals:
<button className={`${styles.button} ${isActive ? styles.active : ''}`}>
Submit
</button>
π 5. When to Use
- You want traditional CSS with scoped behavior.
- You donβt want to set up CSS-in-JS or utility frameworks.
- Good balance of simplicity and control for small/medium projects.