Tuomas Toivonen
Tuomas Toivonen

Reputation: 23522

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?

Upvotes: 5

Views: 14588

Answers (3)

Shanky Munjal
Shanky Munjal

Reputation: 671

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'})
}

Upvotes: 3

Kokovin Vladislav
Kokovin Vladislav

Reputation: 10421

Toggle css class in React

<div className={isRed && "red"}></div>

let isRed = true;
//result
<div class="red"></div>

let isRed = false or null or undefined or "" or 0;
//result
<div class=""></div>

if there is another class u may use

<div className={"element "+ (isRed ? "red":"")}></div>

or put result in varaiable

let modificator = isRed ? "red":"";
<div className={"element "+ modificator}></div>

the same with open/close classes

let modificator = isOpen ? "open" : "close";
<div className={"element "+ modificator}></div>

if you want to not render some element

{isShow && <div className="element"></div> }

It is common practice ,using logic and ternary operators for that.

Upvotes: 1

Gosha A
Gosha A

Reputation: 4570

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} />

Upvotes: 12

Related Questions