When attaching 'click' event listener to the DOM, elements like Link or some buttons with onClick listener that are part of the ref are not reacting to the click event. If no action is taken - it works fine, but when I call for example toggleMenu() it just stops there. Something you usually see after applying e.stopPropagation() or e.preventDefault()...
import React, { useRef, useEffect } from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Link } from "react-router-dom";
function App() {
const menuRef = useRef();
const onDocumentClick = ({ target }) => {
if (menuRef.current.contains(target)) {
// event stops here if any action is taken
// even an alert
// comment this line to see the difference
alert('This is not button\'s alert');
}
};
useEffect(() => {
document.addEventListener("mousedown", onDocumentClick);
return () => {
document.removeEventListener("mousedown", onDocumentClick);
};
}, []);
return (
<BrowserRouter>
<div ref={menuRef} className="App">
<Link to="/test">Not working</Link>
<p>Button should show an alert saying 'clicked'</p>
<button onClick={() => alert("clicked")}>Doesn't work</button>
</div>
<br/>
<br/>
<br/>
<p>Outside of 'ref'</p>
<Link to="/test">Works</Link>
<p>........................</p>
<button onClick={() => alert("clicked")}>Works</button>
</BrowserRouter>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
I have the code on https://codesandbox.io/s/24z2v670wr if you'd like to test it out.
I think what happens is you're catching mousedown on the document, pop up an alert, and then click "OK" in the alert box. In order for a click event to happen, you need to trigger mousedown and mouseup. However, mouseup never has a chance to happen – at least for the button – because you released the mouse button when you clicked that "OK" in the alert box. So, this is expected behavior.
O boy, obviously!
Changed from mousedown to click and all OK!

Thank you
Now if somebody can tell me how to close this issue, we done here!
I'm new here :)
Most helpful comment
Now if somebody can tell me how to close this issue, we done here!
I'm new here :)