Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React onClick event for multiple divs

Tags:

reactjs

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>

        );
    }
});
like image 674
jgb Avatar asked Mar 10 '23 22:03

jgb


1 Answers

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.

like image 142
Hardik Modha Avatar answered Mar 27 '23 15:03

Hardik Modha