I'm trying to create an onClick event that adds a classname for each of these elements without writing out three different functions. The event is fired on all three when one is clicked, however. How can I modify this so that the onClick only works for the one that is clicked?
const userVote = React.createClass({
getInitialState: function() {
return {
condition: false
}
},
handleClick: function() {
this.setState({
condition: !this.state.condition
});
},
render() {
return(
<div onClick={this.handleClick} className= { this.state.condition ? "positive active" : "positive"}></div>
<div onClick={this.handleClick} className= { this.state.condition ? "neutral active" : "neutral"}>Not Sure</div>
<div onClick={this.handleClick} className= { this.state.condition ? "negative active" : "negative"}></div>
);
}
});
As you said, you want only one div active at a time. You can maintain a single state variable which will keep track of an active div.
handleClick: function(divName) {
this.setState({
activeDiv: divName
});
}
<div>
<div onClick={() => this.handleClick('div1')} className= { this.state.activeDiv === 'div1' ? "positive active" : "positive"}>Div1</div>
<div onClick={() => this.handleClick('div2')} className= { this.state.activeDiv === 'div2' ? "neutral active" : "neutral"}>Div2</div>
<div onClick={() => this.handleClick('div3')} className= { this.state.activeDiv === 'div3' ? "negative active" : "negative"}>Div3</div>
</div>
I've created a state variable named activeDiv
which will keep track of an active div, and when applying className
you can check whether the current div
is active or not.
Here, is the working Plunker: Plunker (ES6 Syntax)
JSFiddle (ES5 Syntax)
PS: You'll need to open browser console to see the results.
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