# clsx

clsx (opens new window) is a simple library that lets you toggle class names easily. You can install it using npm install clsx or yarn add clsx.

Please take a look at its documentation for more details, but here's the basic usage:

Suppose that you want to create an Alert component which accepts type, which can be 'success' or 'error'. If it's 'success', you want the text color to be green. If it's 'error', you want the text color to be red. You can first write a CSS module (e.g. alert.module.css (opens new window) like this:

.success {
  color: green;
}
.error {
  color: red;
}
1
2
3
4
5
6

And use the clsx module in components/alert.js (opens new window):

import styles from './alert.module.css';
import clsx from 'clsx';

export default function Alert({ children, type }) {
  return (
    <div
      className={clsx({
        [styles.success]: type === 'success',
        [styles.error]: type === 'error',
      })}
    >
      {children}
    </div>
  );
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Notice how the object passe to clsx has as keys the class names, but since the class names have been manipulated, we have to resort to the expression [styles.success]to evaluate the name.

# References

Last Updated: 2 months ago