Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle css class in React

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?

like image 257
Tuomas Toivonen Avatar asked Dec 08 '22 22:12

Tuomas Toivonen


2 Answers

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} />
like image 115
Gosha A Avatar answered Dec 10 '22 10:12

Gosha A


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'})
}
like image 43
Shanky Munjal Avatar answered Dec 10 '22 11:12

Shanky Munjal