I have a ponent 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 ponent onClick event propagation when the child onClick event fires?
I have a ponent 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 ponent onClick event propagation when the child onClick event fires?
Share Improve this question edited Jul 29, 2017 at 18:44 Andy Baird asked Jul 26, 2017 at 17:37 Andy BairdAndy Baird 6,2284 gold badges45 silver badges64 bronze badges 2- Possible duplicate of jQuery / Bootstrap: Child DIV opens up Parent Modal – Shubham Khatri Commented Jul 26, 2017 at 18:03
- No it's not even a little bit. – Andy Baird Commented Jul 26, 2017 at 22:00
2 Answers
Reset to default 13You 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
}
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./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="react"></div>