How to add multiple classes to a ReactJS Component?
I use classnames when there is a fair amount of logic required for deciding the classes to (not) use. An overly simple example:
...
var liClasses = classNames({
'main-class': true,
'activeClass': self.state.focused === index
});
return (<li className={liClasses}>{data.name}</li>);
...
That said, if you don't want to include a dependency then there are better answers below.
Concat
No need to be fancy I am using CSS modules and it's easy
import style from '/css/style.css';
<div className={style.style1+ ' ' + style.style2} />
This will result in:
<div class="src-client-css-pages-style1-selectionItem src-client-css-pages-style2">
In other words, both styles
Conditionals
It would be easy to use the same idea with if's
const class1 = doIHaveSomething ? style.style1 : 'backupClass';
<div className={class1 + ' ' + style.style2} />
ES6
For the last year or so I have been using the template literals, so I feel its worth mentioning, i find it very expressive and easy to read:
`${class1} anotherClass ${class1}`
Just use JavaScript.
<li className={[activeClass, data.klass, "main-class"].join(' ')} />
If you want to add classes based keys and values in an object you can use the following:
function classNames(classes) {
return Object.entries(classes)
.filter(([key, value]) => value)
.map(([key, value]) => key)
.join(' ');
}
const classes = {
'maybeClass': true,
'otherClass': true,
'probablyNotClass': false,
};
const myClassNames = classNames(classes);
// Output: "maybeClass otherClass"
<li className={myClassNames} />
Or even simpler:
const isEnabled = true;
const isChecked = false;
<li className={[isEnabled && 'enabled', isChecked && 'checked']
.filter(e => !!e)
.join(' ')
} />
// Output:
// <li className={'enabled'} />
I use ES6
template literals. For example:
const error = this.state.valid ? '' : 'error'
const classes = `form-control round-lg ${error}`
And then just render it:
<input className={classes} />
One-liner version:
<input className={`form-control round-lg ${this.state.valid ? '' : 'error'}`} />