How to toggle a presence of css class on element in React with boolean value? In Angular 2 I could just do [class.red]="isRed"
. How to do familiar thing in React?
In React, elements get their classes using a syntax like this
<div className="some-class" />
Note however that JSX allows attribute values to be JS expressions
<div className={"some-" + "class"} />
Which can be used generate a class name based on some logic, such as your boolean check
<div className={isRed ? "red" : null} />
If your element should also has some classes that don't depend on a variable and should always be applied, this can be achieved with
<div className={"my-class " + (isRed ? "red" : null)} />
At which point it seems to start to get messy and it's probably better to extract that into a local variable instead
var className = "my-class " + (isRed ? "red" : null);
<div className={className} />
React itself doesn't provide an utility function to deal with this, however the boolean pattern is so common, there is a package called classnames that will turn the above into
var className = cx("my-class", { "red": isRed });
<div className={className} />
You can use state for that.
<div className={this.state.styleClass}></div>
On any event you can change the class like
handleClick: function(){
this.setState({styleClass: 'red'})
}
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