How do you add a CSS class to an existing REACT element on click?
I have a JSFiddle created: https://jsfiddle.net/5r25psub/
In the fiddle, the code only wor
https://jsfiddle.net/ajvf50s6/3/
Most probably, you should better do a verification based on the className
, not on the color
state property:
handleClick: function(){
if (this.state.className === 'blue'){
this.setState({className: "green"});
} else {
this.setState({className: "blue"});
}
}
Also, as @Omarjmh mentioned, you have a typo in your code. {className = " green"}
is wrong assignment.
You need to add all state parameters to getInitialState
, right now the only thing you have is color
, so this.state.color
is the only thing in there
When you set your state to className: something, that is the only thing in there now, even color is gone...and that is why the initial color is the normal bland gray
you have a syntax error in setState as well, its not
this.setState({className = " green"});
It should be:
this.setState({className: " green"});
Finally, React.render
is deprecated, you need to use ReactDOM.render
now
Fiddle: https://jsfiddle.net/omarjmh/69z2wepo/36597/
Rather than using two state variables, you can do like this.
Since the initial state of color is blue, you can change the handleClick function as :
handleClick: function(){
if (this.state.color === 'blue'){
this.setState({color : "green"});
} else {
this.setState({color: 'blue'});
}
}
And, for the className, consider a variable :
let colorClass= this.state.color === "blue" ? "blue" : "green"
Now, replace the className as below and you need to enclose that object where you call div class.
return <button className={colorClass} onClick={this.handleClick}>My background is: {this.state.color}, Click me to change</button>;
I hope it works fine.
You can use the module classnames
found here:
https://www.npmjs.com/package/classnames
So you would do something like:
getClassNames() {
return classNames({
'blue': this.state.clicked,
'green': !this.state.clicked
});
},
render () {
return <button className={this.getClassNames()} onClick={this.setState({clicked: !this.state.clicked})>
}