Clean • Professional
When building large-scale React applications, managing styles can become tricky. Global CSS files can cause class name conflicts and make it hard to maintain your app. This is where CSS Modules come in.
CSS Modules provide component-level scoped styles, meaning each CSS class is local to the component that imports it. This ensures clean, maintainable, and reusable styling.
.module.css extension.styles object to apply class names.Button.module.css
.button {
background-color: #007bff;
color: white;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
border: none;
}
.button:hover {
background-color: #0056b3;
}
Button.js
import React from "react";
import styles from "./Button.module.css";
function Button({ text }) {
return <button className={styles.button}>{text}</button>;
}
export default Button;
styles is an object where each key corresponds to a CSS class.You can apply different styles based on props:
Button.module.css
.primary {
background-color: #007bff;
color: white;
}
.secondary {
background-color: #6c757d;
color: white;
}
.button {
padding: 10px 20px;
border-radius: 5px;
border: none;
cursor: pointer;
}
Button.js
import React from "react";
import styles from "./Button.module.css";
function Button({ text, type }) {
const buttonClass =
type === "primary" ? styles.primary : styles.secondary;
return <button className={`${styles.button} ${buttonClass}`}>{text}</button>;
}
export default Button;
buttonClass dynamically applies styles based on the type prop.Card.module.css
.card {
border: 1px solid #ddd;
padding: 20px;
border-radius: 10px;
background-color: #f9f9f9;
}
.cardTitle {
font-size: 20px;
font-weight: bold;
margin-bottom: 10px;
}
Card.js
import React from "react";
import styles from "./Card.module.css";
function Card({ title, children }) {
return (
<div className={styles.card}>
<h3 className={styles.cardTitle}>{title}</h3>
<div>{children}</div>
</div>
);
}
export default Card;
| Feature | Benefit |
|---|---|
| Scoped CSS | No global conflicts, styles are local to components |
| Reusable | Each component can have its own styles |
| Dynamic Styling | Works with props for conditional styling |
| Familiar CSS Syntax | You can use media queries, pseudo-classes, transitions |
| Maintainable | Easier to read, especially in large apps |
This will render two buttons with independent, scoped styles, avoiding conflicts with other components.
import React from "react";
import styles from "./Button.module.css";
function App() {
return (
<div>
<Button text="Primary Button" type="primary" />
<Button text="Secondary Button" type="secondary" />
</div>
);
}
export default App;