CSS Modules in React
19 January, 2023
0
0
0
Contributors
Introduction
While writing inline styles is okay for small apps, it does not scale well when we move to bigger applications that need to share styles. One of the solution to this scalability problem is CSS modules.
When we use CSS modules to style a React app, we create a separate CSS file and we import it as a module into the React file. There is also no issue of clashing styles in this methodology because each module file is independent.
Example of CSS module in React
Here is an example of using CSS modules in a React component:
First, create a CSS file for the component:
/* MyButton.module.css */
.button {
background-color: blue;
color: white;
font-size: 16px;
padding: 10px 20px;
}
Then, import the CSS file into the component and use the class names from the CSS module:
import React from 'react';
import styles from './MyButton.module.css';
function MyButton() {
return (
<button className={styles.button}>Click me!</button>
);
}
In this example, the CSS module is imported as a JavaScript object where the keys are the class names from the CSS file and the values are the generated class names. These generated class names are unique, so they won't conflict with class names from other CSS modules or from global styles.
Applying styles selectively
You can also use the class names from the CSS module in JavaScript expressions:
import React from 'react';
import styles from './MyButton.module.css';
function MyButton(props) {
const className = props.large ? styles.largeButton : styles.button;
return (
<button className={className}>Click me!</button>
);
}
In this example, the class name of the button is determined by the large
prop. If large
is true
, the largeButton
class will be applied, otherwise the button
class will be applied.
Conclusion
CSS modules are a great way to style individual components in a way that is modular and scalable. They also make it easy to avoid class name collisions, because the class names are locally scoped to the component.