Skip to main content

CSS Modules

CSS Modules are a styling solution for React applications that enables you to create component-specific styles. With CSS Modules, you can write CSS that is scoped locally to a single component, avoiding global style conflicts. In this tutorial, we'll learn how to use CSS Modules in React applications, along with sample code, explanations, and best practices.

Setting up CSS Modules

To use CSS Modules in a Create React App project, you need to follow the file naming convention Component.module.css. If you're using a custom Webpack configuration, you'll need to configure the CSS loader to enable CSS Modules.

Here's an example of a CSS Module file:

CSS
/* Button.module.css */
.button {
background-color: blue;
color: white;
padding: 10px;
border-radius: 5px;
}

Using CSS Modules

To use a CSS Module in your React component, you need to import the styles as an object and apply them to your elements using the className attribute.

Here's an example of using a CSS Module in a functional component:

JavaScript
import React from 'react';
import styles from './Button.module.css';

function CustomButton() {
return <button className={styles.button}>Click me</button>;
}

export default CustomButton;

In this example, we imported the styles from the Button.module.css file as an object and applied the button class to the button element using the className attribute.

Best Practices

When using CSS Modules in React, it's essential to follow best practices to ensure maintainable and efficient code:

  1. Use descriptive class names: Since CSS Modules scope your styles locally, you don't need to worry about naming conflicts. Use descriptive class names that are easy to understand.
  2. Organize styles per component: Create a separate CSS Module file for each component to keep your styles organized and modular.
  3. Combine with global styles: Use CSS Modules for component-specific styles and combine them with global styles for general layout and theming.

Conclusion

CSS Modules provide an excellent solution for creating component-specific styles in React applications. By scoping your styles locally, you can avoid global style conflicts and ensure maintainable and efficient code. Using CSS Modules in combination with global styles will help you build organized and modular React applications with ease.