Andy Baird Andy Baird - 1 year ago 59
React JSX Question

Cancel onClick event of parent component in child component

I have a component that looks like:

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

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?

Answer Source

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


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 ) {
  // ... do stuff
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download