3
votes

I have a component that looks like:

<ParentComponent onClick={this.doSomething}>
  <ChildComponent onClick={this.doSomethingElse} />
</Parent>

If I click on the ChildComponent, both doSomethingElse and doSomething fire. How can I cancel the parent component onClick event propagation when the child onClick event fires?

2
No it's not even a little bit. - Andy Baird

2 Answers

12
votes

You should add the line e.stopPropagation(); to the top of your this.doSomethingElse event handler.

Event.stopPropagation().

Prevents further propagation of the current event in the capturing and bubbling phases.

So when you use e.StopPropagation() in an event handler it prevents the event from bubbling up to ancestors and triggering their event handlers.

Make sure to include e as an argument of your this.doSomethingElse method.

doSomethingElse( e ) {
  e.stopPropagation();
  // ... do stuff
}
3
votes

If you wish to avoid duplicating events, use stopPropagation function.

class App extends React.Component {
  
  firstHandle = () => {
    console.log('parent');
  }
  
  secondHandle = (e) => {
    e.stopPropagation();
    console.log('child');
  }
  
  render() {
    return (
      <div onClick={this.firstHandle}>
        Parent
        <div onClick={this.secondHandle}>child</div>
      </div>
    );
  }
}


ReactDOM.render(
  <App />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="react"></div>