stackjlei
stackjlei

Reputation: 10035

Change react jsx class dynamically without DOM manipulation

I'm using jsx react and want to set a class dynamically while keep another class static so I want something like the below to keep class type but have an additional dynamic class change change to class big or small or whatever.

<p className="type {change}">{pokeType}</p>

Is there a way to do something like this without using element.setAttribute or document.getElementById...className or jQuery stuff? Or is it only possible to go through this kinda thing with DOM manipulation?

Upvotes: 1

Views: 185

Answers (1)

Lyubomir
Lyubomir

Reputation: 20027

You need to have change in your component's state:

this.setState({ change: 'myClass1'})

// will yield <p className="type myClass1">...</p>
<p className={`type ${this.state.change}`}>{pokeType}</p> 

this.setState({ change: 'myClass2'})

// will yield <p className="type myClass2">...</p>
<p className={`type ${this.state.change}`}>{pokeType}</p> 

Upvotes: 1

Related Questions