I have a simple list:
<li onClick={handleRowClick}>
<input type="checkbox" onClick={handleCheckboxClick} />
...
</li>
When I click in any place on the li (except its checkbox child), handleRowClick executes.
When I click on the checkbox, it always executes in this order:
row
row
checkbox
Here's what I've tried
- using
onClickCaptureon each: checkbox, li, and both - calling
e.stopPropagation()on each: checkbox, li, and both - calling
e.nativeEvent.stopPropagation()on each: checkbox, li, and both - calling
e.nativeEvent.stopImmediatePropagation()on each: checkbox, li, and both - calling
e.nativeEvent.preventDefault()on each: checkbox, li, and both
With the code above, at some point the order became
row
checkbox
But the row is always executed BEFORE the checkbox, so I can't see how make them not overlap.
Also worth mentioning that both handlers have logic, that need to happen, so making the row never execute any code is not an option.
This seems like a trivial thing, like I should know the answer to this. What am I missing?
Edit
Here's the minimal reproducible example: https://codesandbox.io/s/shy-shape-u1me4?file=/src/App.js
In the example above I stripped a lot of things like CSS classes. While doing that, I realised that what I'm actually clicking is a label for the checkbox, and the checkbox is "hidden" in my app.
I solved the problem by moving the event handler to the label instead of the checkbox, and running:
e.stopPropagation()to prevent propagation to the parentli.e.preventDefault()to prevent the label to trigger the checkboxes o'clock, which would also cause the event to propagate to theliabove.