I am new to ReactJS and JSX and I am having a little problem with the code below.
I am trying to add multiple classes to the className
attribute on eac
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
It would be easy to use the same idea with if's
const class1 = doIHaveSomething ? style.style1 : 'backupClass';
<div className={class1 + ' ' + style.style2} />
For the last year or so I have been using the template literals, so I feel its worth mentioning, i find it very expression and easy to read:
`${class1} anotherClass ${class1}`
Maybe classnames can help you.
var classNames = require('classnames');
classNames('foo', {'xx-test': true, bar: false}, {'ox-test': false}); // => 'foo xx-test'
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'} />
No need for external libraries - just use ES6 template strings:
<i className={`${styles['foo-bar-baz']} fa fa-user fa-2x`}/>
I use rc-classnames package.
// ES6
import c from 'rc-classnames';
// CommonJS
var c = require('rc-classnames');
<button className={c('button', {
'button--disabled': isDisabled,
'button--no-radius': !hasRadius
})} />
You can add classes in any format (Array, Object, Argument). All truthy values from arrays or Arguments plus keys in objects that equal to true
get merged together.
for example:
ReactClassNames('a', 'b', 'c') // => "a b c"
ReactClassNames({ 'a': true, 'b': false, c: 'true' }) // => "a c"
ReactClassNames(undefined, null, 'a', 0, 'b') // => "a b"
Create a function like this
function cssClass(...c) {
return c.join(" ")
}
Call it when needed.
<div className={cssClass("head",Style.element,"black")}><div>