Table of Contents
- Introduction
- The issue with using global styles
- What are CSS Modules and why use them?
- What is the classnames package and how to use it?
- Classnames and CSS Modules Integration
- Conclusion
Introduction
As software developers, we constantly strive to build maintainable code, and using CSS modules and the âclassnamesâ package for styling your React application is a great way to do that.
If youâre a beginner React developer youâve probably tried using a global stylesheet for your CSS or maybe even sass with the 7-1 pattern or something alike, while thatâs certainly an option, weâll look at the downsides of it and the advantages of using CSS modules and/or the âclassnamesâ package instead, which are both powerful tools that can enhance the development process and improve the organization of styles in React applications.
So in this article, we will explore how to use them to achieve modular and maintainable styling in React.
The issue with using global styles
As mentioned above, one common approach to styling React components is through the use of global stylesheets. While this method may suffice for smaller projects, it becomes challenging to manage as the codebase grows, and thatâs when you may encounter some issues.
The main issue has to do with scope and specificity, since global stylesheets can lead to naming conflicts and specificity issues when different components use the same class names.
It may be easy to avoid components using the same class names when the project is small but it becomes a nightmare to maintain when itâs a big project and several developers are working on it. Itâs challenging to isolate and manage styles for individual components, leading to unexpected visual discrepancies.
The same applies when using sass with the 7-1 pattern or even having each component along with its styles file in its own folder.
It could happen for example that thereâs a component which has a container-box class name, and youâre requested to build some new functionality and you create a component and use the same class name (without knowing the class already exists) in your component with your own styles, depending on the build process either your component styles or the ones for the component that already existed will be overwritten.
Thatâs when CSS modules come to the rescue âš
What are CSS Modules and why use them?
CSS modules provide a solution to the problems associated with global stylesheets, itâs a popular approach to scoping CSS styles locally, ensuring encapsulation and eliminating naming conflicts by creating an unique class name for each component, which promotes modularity and makes CSS code much easier to maintain and refactor.
Besides that, by using CSS modules, the styles will be co-located with their corresponding components, which makes it easier for developers to understand and modify styles without worying about affecting other parts of the application.
To use CSS Modules in a React project, you need to set up the necessary build tools, but this tipically is preconfigured out of the box with most of the tools used currently to start a React application, such as Vite, NextJS or Gatsby, even create-react-app (although itâs no longer recommended to use CRA for your React projects), which makes the setup process seamless.
Youâre probably thinking by now (I hope đ ) âOk, enough convincing, how do I use them? đâ well, fortunately itâs extremely easy!
Letâs say you have a Button.jsx component, in the src/components/Button folder, to use CSS modules, simply create a regular CSS file in the same folder and add .module.css extension to it, for example button.module.css (technically you can call it anything you want but I find it a better practice to name it the same as your component), and it also works with sass/scss, just change .css for .scss/.sass.
Next, add the desired class styles to your CSS file, for example:
.btn {
cursor: pointer;
border: none;
}
And then you import the CSS module in your React component and use it as such:
// SwitchButton.jsx
import styles from './button.module.css';
const SwitchButton= () => {
return <button className={styles.btn}>Click me</button>;
}
Thatâs it! the build process will replace the CSS class with an unique name similar to this _btn_1411r_23, so if you or another developer, by any chance, add a new .btn class in another component, the build process will add an unique id to it so neither of the styles will be overwritten đđŒ
CSS modules also allow you to dynamically assign classes, which is great! but, it also has a bad side, which is that if you need to add multiple classes, it can get pretty wordy, especially if youâre also conditionally adding classes, for example:
// SwitchButton.jsx
import styles from './button.module.css';
const SwitchButton = ({ isDisabled, border, type }) => {
return (
<button
className={`
${styles.btn}
// Dynamic class
${styles[type]}
// Conditional classes
${isDisabled ? styles.isDisabled : ''}
${border ? styles.border : ''}
`}
>
Click me
</button>
)
}
And thatâs where the 'classnames' packages can help us! đđŒ
What is the classnames package and how to use it?
The Classnames package is a utility library that provides a convenient way to conditionally apply CSS classes to elements. It simplifies the process of conditionally styling components based on different states or props.
To use the Classnames package, you first need to install it with npm install classnames and then you simply import it in the component where you wish to use it. First, letâs see an example on how to use it by itself, without CSS modules, hereâs the previous example, using classnames:
// SwitchButton.jsx with Classnames and without CSS modules
import classNames from 'classnames';
import './button.css';
const SwitchButton = ({ isDisabled, border, type }) => {
return (
<button
className={classNames('btn', type, {
'active': isDisabled,
border
})}
>
Click me
</button>
)
}
You can see that we passed a string, then a dynamic class based on the type prop and then an object where we place our conditional classes.
In the object the key represents the name of the class and the value represents the conditional, so in this case the class is âactiveâ and it will only be applied if isActive is true.
You can pass any conditional here, it doesnât necessarily have to be a variable or a prop, the conditional could be type === 'success' for example. And just like any object, you can also omit the value if the value an the key have the same name, as in the case of âborderâ.
This is much better right? much less wordy. You might say âof course itâs better, weâre not using CSS modules, itâd be less wordy too if we used regular CSSâ, well actually no đ
youâll see later that we can get almost the same result using CSS modules, and itâs definitely less wordy than handling the conditional classes with regular CSS:
// SwitchButton.jsx without Classnames and without CSS modules
import './button.css';
export const SwitchButton = ({ isDisabled, border, type }) => {
return (
<button
className={`
btn
${type}
${isDisabled ? 'active' : ''}
${border ? 'border' : ''}
`}
>
Click me
</button>
)
}
So handling classes with âclassnamesâ is still a great choice if youâre not using CSS modules, but using only the package does not solve the original issue of class naming conflicts, so letâs see how we can implement âclassnamesâ along with CSS Modules and get the best of both worlds âš
Classnames and CSS Modules Integration
There are 2 ways in which we can do this, I find the first one much better than the second, but weâll see both in case you canât use the first one for whatever reason.
1. Bind version
Letâs see the code first:
import styles from "./button.module.css";
// import from classnames/bind
import classNames from 'classnames/bind'
// bind the styles to classNames
const cx = classNames.bind(styles);
export const SwitchButton = ({ isDisabled, border, type }) => {
return (
<button
/* use them almost as if you were using */
/* a regular/global CSS stylesheet */
className={cx('btn', [type], {
'active': isDisabled,
border
})}
>
Click me
</button>
);
};
This is what I meant by getting almost the same result by using classnames + CSS modules as if we were using global styles. As you can see here, there are only some few changes that we need to do (as stated in the comments in the code), but the end result is great, much more concise than using only CSS modules.
2. No Bind version
Again, letâs see the code first:
import styles from "./button.module.css";
// import classNames as if not using CSS modules
import classNames from 'classnames'
export const SwitchButton = ({ isDisabled, border, type }) => {
return (
<button
/* use the classes by accessing them through */
/* the styles object */
className={classNames(styles.btn, [styles.type], {
[styles.active]: isDisabled,
[styles.border]: border
})}
>
Click me
</button>
);
};
You probably can see why I prefer the previous way, this one is less concise since we need to apply the styles by accessing the âstylesâ object, as we first saw when using CSS modules, but Iâve worked in some projects where the first way hasnât worked for me (probably due to environment or compiling configurations) so Iâve had to settle with the second đ
Conclusion
In this article, we have explored the usage of CSS Modules and the Classnames package in React. We have seen how CSS Modules provide local scoping and better organization of styles, while the Classnames package simplifies conditional styling. By leveraging these tools, you can enhance readability, maintainability, and scalability, allowing for a better development experience.
I hope the article was useful for you đđŒ and if you have any questions please feel free to leave them in the comments below. Happy coding! đ€đŒ
Top comments (2)
thanks. i was looking for something like this
Glad I could help! :D (I'm sorry for the super late reply xD)