Conditional ClassName in React
Robin Wieruch •
If we would be only using JavaScript, it would be possible to create a conditional React className attribute this way:
javascript
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:
javascript
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:
javascript
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 Styled Components.