CSS Modules
What Are CSS Modules?
CSS Modules are a CSS file in which all class names and animation names are scoped locally by default. This means that you can have two components with the same CSS class name, and they won't affect each other because the CSS is not global, but local to the component.
Why Use CSS Modules?
The main advantage is that you can avoid naming collisions. It's also easier to maintain your code because you know that the CSS is scoped to the component. This is especially useful in large projects where it can be hard to avoid duplicate class names.
How to Use CSS Modules in React?
To use CSS Modules in React, you need to use a specific file naming convention. You should name your CSS files as ComponentName.module.css
. The .module.css
extension is what tells React to treat this file as a CSS Module.
For example, if you have a Button
component, you would name your CSS file as Button.module.css
.
Here's an example of how to use a CSS Module in a React component:
import React from 'react';
import styles from './Button.module.css';
const Button = () => {
return (
<button className={styles.button}>
Click me
</button>
);
};
export default Button;
In the Button.module.css
file, you would define your styles like this:
.button {
background-color: blue;
color: white;
padding: 10px;
}
When you import your CSS Module into a React component, you can access your styles as properties on the imported styles
object. In the example above, we access the .button
class by using styles.button
.
Overriding CSS Modules
If you want to override the CSS from a CSS Module, you can do so by using the :global
selector.
Here's an example:
:global(.button) {
background-color: red;
}
The :global
selector makes the CSS global, so it can override the local CSS from the CSS Module.
CSS Modules and Composability
One of the great features of CSS Modules is the ability to compose styles. This means that you can create a base style and then extend it with additional styles.
Here's an example:
.button {
background-color: blue;
color: white;
padding: 10px;
}
.bigButton {
composes: button;
font-size: 2em;
}
In this example, we define a .button
style and then we create a .bigButton
style that extends the .button
style. The composes
keyword is used to extend another style.
You can then use the .bigButton
style in your React component like this:
import React from 'react';
import styles from './Button.module.css';
const BigButton = () => {
return (
<button className={styles.bigButton}>
Click me
</button>
);
};
export default BigButton;
The button will have the same background color, color, and padding as the .button
style, but it will also have a bigger font size.
That's it! You now know how to use CSS Modules in React. They are a powerful tool to scope your CSS and avoid naming collisions, and they also offer great features like composability. Happy coding!