<div onClick={()=>do_stuff()}>
<div classname="div-1"></div>
<div classname="div-2"></div>
<div classname="div-3"></div>
<div classname="div-4"></div>
<div classname="div-5"></div>
</div>
When the parent is clicked, it should only call the callback if for example, the click did not include div-4
, div-5
etc.
How to implement this in React?
2
Answers
You could check
event.target
withElement#matches
.event.stopPropogation()
solves this very easily.With nested HTML elements, click events work their way up the heirarchy. Child components have their onclicks fire first. Parent components onclicks fire after. Doesn’t matter how deeply nested the elements are, click events will always fire at the lowest nested level first, eventually ‘propogating’ all the way back up. You can stop the clicks from ‘propogating’ any further up by calling
stopPropogation()
. Once the callback with the stop propogation is executed, the rest of the call stack is simply erased.