Conditional ClassName in React

 by Robin Wieruch
 - Edit this Post

If we would be only using JavaScript, it would be possible to create a conditional React className attribute this way:

const Box = ({ status, children }) => {
let classNames = ['box'];
if (status === 'INFO') {
classNames.push('box-info');
}
if (status === 'WARNING') {
classNames.push('box-warning');
}
if (status === 'ERROR') {
classNames.push('box-error');
}
return (
<div className={classNames.join(' ')}>
{children}
</div>
);
}

Fortunately, there is one neat helper library for conditional classnames in React: clsx:

import cs from 'clsx';
const Box = ({ status, children }) => {
const classNames = cs('box', {
'box-info': status === 'INFO',
'box-warning': status === 'WARNING',
'box-error': status === 'ERROR',
});
return (
<div className={classNames}>
{children}
</div>
);
}

It works perfectly with CSS modules too:

import cs from 'clsx';
import styles from './style.css';
const Box = ({ status, children }) => {
const classNames = cs('box', {
[styles.boxInfo]: status === 'INFO',
[styles.boxWarning]: status === 'WARNING',
[styles.boxError]: status === 'ERROR',
});
return (
<div className={classNames}>
{children}
</div>
);
}

And could also be used for optional classNames in .

Keep reading about 

This tutorial is outdated. Please read over here everything you need to know about React Ref . In the past there has been a lot of confusion around the ref attribute in React. The attribute makes…

Can you use conditional React Hooks in React components? Technically: No. However, if you know about how React Hooks work internally, you can make conditional hooks work for you. Let's take the…

The Road to React

Learn React by building real world applications. No setup configuration. No tooling. Plain React in 200+ pages of learning material. Learn React like 50.000+ readers.

Get it on Amazon.