How to style components with CSS modules in React
Using CSS modules provides scoped styling and eliminates CSS conflicts in React applications while maintaining the benefits of traditional CSS workflows.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented CSS modules in numerous React projects for component isolation, theme customization, and maintainable styling architectures in enterprise applications.
From my expertise, the most effective approach is to use .module.css
files with imported class names.
This method provides automatic scope isolation, prevents style leakage between components, and maintains excellent development experience with standard CSS syntax.
Use CSS modules with .module.css
extension and import class names for scoped component styling.
// Button.module.css
.button {
padding: 8px 16px;
border: none;
border-radius: 4px;
}
.primary {
background-color: #007bff;
color: white;
}
// Button.jsx
import styles from './Button.module.css'
function Button({ primary, children }) {
return (
<button className={`${styles.button} ${primary ? styles.primary : ''}`}>
{children}
</button>
)
}
CSS modules automatically generate unique class names by appending hash identifiers, preventing global CSS conflicts. Import the CSS module as an object where keys are your original class names and values are the generated unique names. Access classes using dot notation styles.button
or bracket notation styles['button-primary']
for kebab-case names. CSS modules work with all CSS features including pseudo-classes, media queries, and CSS preprocessors like Sass.
Best Practice Note:
This is the same approach we use in CoreUI React components for isolated styling and theme customization.
Combine multiple classes using template literals or the classnames
library: className={classNames(styles.button, { [styles.primary]: primary })}
for cleaner conditional styling.