Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React event propagation doesn't really stop

Tags:

reactjs

var Vote = React.createClass({
    onVote(event){
      console.log("event triggered");
      event.stopPropagation();
      event.nativeEvent.stopImmediatePropagation();
    },

    render: function() {
     return <div>
      <ul>
       <li onClick={this.onVote}>
        <input 
        type="radio" 
        name="vote_for_president" 
        value="donald"
        onChange={this.onVote}/>
        Donald
    </li>
    <li onClick={this.onVote}>
        <input type="radio" 
      name="vote_for_president" 
      value="clinton"
      onChange={this.onVote}
      />Clinton
    </li>
  </ul>
 </div>;
 }
});

I need to trigger an event on the click of list item and on change of radio button and have perform the same action. Issue here is the event is being called twice when I click on the radio input and event propagates to click event of list item. Stop propagation and native stop methods isn't working.

The intention here is I want the whole li row to be clickable and event should not be called twice when click on radio button.

Here is jsfiddle https://jsfiddle.net/dbd5f862/

like image 393
srinivas Avatar asked Jan 06 '23 06:01

srinivas


1 Answers

The change and click events are different events. When a radio button is being clicked, its change event will fire. But, the list item was also clicked, and its click event will therefore fire at the same time. Stopping the propagation of the change event won't affect the click event.

To solve this, you could stop the propagation of the radio button's click event:

<li onClick={this.onVote}>
  <input 
    ...
    onChange={this.onVote}
    onClick={event => event.stopPropagation()}
  />
  Donald
</li>

Here's an updated fiddle: https://jsfiddle.net/cpwsd3ya/

like image 164
tobiasandersen Avatar answered Jan 21 '23 20:01

tobiasandersen