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: classnames:

import cs from 'classnames';
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 'classnames';
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 

The article is a short how to use CSS Modules in your create-react-app application . It shows you how to setup CSS Modules, but also how to use them in your components. After you have setup your…

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…

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.