I've been musing on how best to conditionally apply a CSS class in React JS. I've seen some answers banding around but there aren't many out there or they're just not as elaborative as I'd like.
Create a new react application or open existing react app. Declare two different CSS style objects named as objectStyle and objectStyleValid with below attributes (in Code). Next we will declare a const variable named “isValid”. Based on its value (true/false) we will try to change the CSS style.
You can use require('file. css') or import('file. css') syntax instead -- that will allow you to use it inside of a conditional. You might need babel-plugin-syntax-dynamic-import for the import() syntax.
You can simply condition class to state, like this:
<div className={ this.state.exampleIsTruthy ? 'yourClass' : '' }> text </div>
or if you want to switch classes based on a state like this:
<div className={ this.state.exampleTrueOrFalse ? 'shown' : 'hidden' }> text </div>
The React documentation on manipulating class names suggests the classnames
NPM package.
The docs for the package are great.
The following snippet is straight from the package README
: Usage section
classNames('foo', 'bar'); // => 'foo bar' classNames('foo', { bar: true }); // => 'foo bar' classNames({ 'foo-bar': true }); // => 'foo-bar' classNames({ 'foo-bar': false }); // => '' classNames({ foo: true }, { bar: true }); // => 'foo bar' classNames({ foo: false, bar: true }); // => 'bar' // lots of arguments of various types classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux' // other falsy values are just ignored classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With