How to conditionally apply CSS classes in React JS

I was thinking about how best to conditionally apply the CSS class in React JS. I saw some answers exchanged around, but there are few of them, or they are simply not as thought out as we would like.

+11
source share
9 answers

Documentation Responsive to manipulating class names offers the class names of the NOG package.

The documents for the package are excellent.

The following snippet directly from the README package: 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' 
+16
source

Without the classNames library, you can simply condition state like this:

 <div className={ this.state.end ? 'hidden' : 'shown' }> text </div> 
+13
source

Use Classnames library https://github.com/JedWatson/classnames

The classNames function takes any number of arguments, which can be a string or an object. If the key value is false, it will not be included in the output.

 var classNames = require('classnames'); var Button = React.createClass({ // ... render () { var btnClass = classNames({ 'btn': true, 'btn-pressed': false, 'btn-over': true }); // output: btnClass = "btn btn-over" return <button className={btnClass}>{this.props.label}</button>; } }); 

Take a look at the document and let me know if you have any questions!

Greetings

+3
source

The solution, which is outlined below by another author in the above comment, works for me

 <div className={ this.state.end ? 'hidden' : 'shown' }>text</div> 

Just add if you want to add more classes and then add a class separated by a space.

+3
source

For the record, I think the answers of the classnames library are the most correct, but if you don't want to pull another dependency, you can roll up your own simple implementation that works like jQuery:

 function getClassBuilder () { return { array: [], add: function (className) { if (this.array.indexOf(className) < 0) { this.array.push(className); } }, remove: function (className) { var index = this.array.indexOf(className); if (index > -1) { this.array.splice(index, 1); } }, toString: function () { return this.array.join(' '); } } } 

then when you need to use it:

 var builder = getClassBuilder(); builder.add('class1'); builder.add('class2'); if (condition) { builder.remove('class1') }; <a href="#" className={builder.toString()}>Button</a> 
+2
source

I will illustrate on boot classes, change the color of the text conditionally: if count = 0, the text will be red, otherwise it will be blue

 class Counter extends Component { state = { count: 6 }; render() { let classes="text-center" //class is reserved word in react.js classes+= (this.state.count===0) ? "text-danger" : "text-primary" return ( <div> <h2 className={classes}>Hello World</h2> </div> ); } formatCount() { const { count } = this.state; return count === 0 ? "zero" : count; } } 
0
source

If you need to add a conditional class to an existing class, it can give you an idea

 <span className={'fa ' + (this.state.dropdownActive ? 'fa-angle-up' : 'fa-angle-down')}></span> 

in this example, I show an arrow icon for a drop-down list depending on the state of the drop-down list. I need to keep the fa class for any occasion to set the range font family, and I only need to switch between fa-angle-up and fa-angle-down .

Same example with template literals

 <span className={'fa ${this.state.dropdownActive ? 'fa-angle-up' : 'fa-angle-down'}'}></span> 
0
source

Many answers suggest that we are talking about conditionally switching CSS classes (ternary if that's enough), but it gets a lot dumber when you don't have to include class names. Multiple ternary ifs with empty false expressions are verbose. An NPM package may be a bit. Function may also be redundant for some.

That's what I'm doing.

 const classNames = [ "className1", condition1 && "className2", condition2 && "className3", condition3 && "className4", ].filter(e => e).join(" "); 
0
source

Ok, so I experimented, and it turned out that there are ways, and it is not as difficult as I thought. This can help those just starting out in React JS.

So, there are two ways to do this and two reasons for adding styles to a string:

(1) Add the class name inside the style attribute as an object so that it can be drawn inside a regular CSS stylesheet, directly inside a JSX file, or used for conditional CSS

EXAMPLE 1

 const classNameAsAPlainObject = { color: '#333333', backgroundColor: '#999999' } <a href="#" className="an-existing-class" style={classNameAsAPlainObject} > Button </a> 

EXAMPLE 2

 const conditionIsSomething = { color: 'red' } <a href="#" className="an-existing-class" style={conditionIsSomething ? 'classNameBasedOnCondition' : ' ' }> Button </a> 

In the second example, two different classes can be declared depending on the desired result, or one class can be declared if the condition is true or none if the condition is false.

(2) Add it to the regular className attribute where a condition is required, but it is mandatory to place existing class names and keep in mind that this method requires styling in a regular CSS file. If the condition is not required, add the class as normal to the className attribute.

EXAMPLE 3

 <a href="#" className={"an-existing-class " + (conditionIsSomething ? 'thisClass' : 'thatClass')}> Button </a> 

EXAMPLE 4

 <a href="#" className={"an-existing-class " + (conditionIsSomething ? 'aClassIsAdded' : ' ')}> Button </a> 

Again, if this condition requires it, one class can be declared or not, as shown in Example 4. Be sure to leave a space in any case after the โ€œexisting classโ€ and before the closing quote, so that is the space for the conditional class.

So, I believe that the general rule is that you add a class and style as an object (as in examples 1 and 2), you can style it in a JSX file, but if you add the class name to the "className" attribute, you You will put it inside a regular CSS file. I have not experimented with this, so I will try. If anyone finds otherwise, please enlighten me.

-3
source

All Articles