I have a div container with a button inside it. Both container and button have onMouseDown listeners. The button's listener, however, stops propagate the event. So:
- when I click on the container, "MouseDown" event is logged into the console,
- when I click on the button, nothing is logged, because button stops event bubbling.
So far so good. However, when I add mousedown listener with addEventListener to the container, it will be called even when I click on the button. So button's stopProgapagation() doesn't stops this listener from executing. Why? How can I fix that? Here is a full demo.
export const App = () => {
const divRef = useRef()
useEffect(() => {
// Shouldn't be executed when I click on the button, but it is.
divRef.current.addEventListener("mousedown", () => console.log("NewMouseDown"))
}, [])
return (
<div onMouseDown={() => console.log("MouseDown")} ref={divRef}>
<button onMouseDown={e => e.stopPropagation()}>Stop propagation</button>
</div>
);
}