CSS Module in React JS
CSS Module in React JS
CSS Modules are a way to scope your CSS to the component where it's defined. In a CSS Module, classes are locally scoped, preventing CSS conflicts between components. In React, we can use CSS Modules to apply styles that are scoped to a specific component without affecting others.
1. How to Use CSS Modules in React
To use CSS Modules in React, you need to import the CSS file as a JavaScript object, where each class name becomes a key in the object. These class names are automatically scoped to the component, ensuring that styles are applied only to the specific component.
// MyComponent.module.css (CSS Module)
.container {
background-color: #f3f4f6;
padding: 20px;
border-radius: 8px;
}
.heading {
color: #4b5563;
font-size: 24px;
font-weight: bold;
}
.button {
background-color: #2563eb;
color: white;
padding: 10px 15px;
border-radius: 5px;
border: none;
cursor: pointer;
}
2. Using CSS Modules in React Component
Once the CSS Module is created, you import it into your React component. The imported object will have the class names as keys, and you can apply them using the `className` attribute.
// MyComponent.js
import React from 'react';
import styles from './MyComponent.module.css'; // Import CSS Module
const MyComponent = () => {
return (
CSS Module Example
);
};
export default MyComponent;
3. Key Points of Using CSS Modules
- **Local Scope**: CSS classes are scoped to the component and do not conflict with other components' styles.
- **Automatic Class Name Hashing**: React automatically hashes the class names to ensure they are unique across the application.
- **No Global Namespace**: Since class names are local, there is no need to worry about global styles conflicting with local ones.
- **Modularity**: CSS Modules make it easier to maintain and reuse styles across different components.
4. Example: Combining Tailwind CSS and CSS Modules
You can combine Tailwind CSS utility classes with CSS Modules to get the best of both worlds: the power of Tailwind's utility-first styling and the encapsulation of CSS Modules.
// MyComponent.module.css (CSS Module)
.card {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.button {
background-color: #2563eb;
color: white;
padding: 10px 20px;
border-radius: 5px;
border: none;
cursor: pointer;
}
// MyComponent.js
import React from 'react';
import styles from './MyComponent.module.css'; // Import CSS Module
const MyComponent = () => {
return (
CSS Modules with Tailwind
);
};
export default MyComponent;
Conclusion
CSS Modules in React provide a way to modularize your styles and avoid class name conflicts, improving maintainability and scalability. When combined with Tailwind CSS, you can leverage utility classes for layout and spacing while using CSS Modules for more complex, component-specific styles.