'React - How to prevent an onMouseDown event listener stopping an onClick JSX function from executing?
I am currently stuck on a problem where the onClick function for a button of a child react component is not being triggered due to a mousedown event listener that has been defined in the parent component. The mousedown event listener closes a dropdown menu defined in the parent component. This appears to be interfering with a button of a child component as when I remove the mouse down event listener, the button's onclick appears to work again. Here is a simplified version of the code:
// Parent Component
this.moreContainerRef = React.createRef();
handleClickOutside(event) {
const clickedOutsideDropdown =
this.moreContainerRef.current &&
!this.moreContainerRef.current.contains(event.target);
if (!clickedOutsideDropdown) return;
this.setState({ moreMenuOpen: false });
}
componentDidMount() {
document.addEventListener('mousedown', this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener('mousedown', this.handleClickOutside);
}
// In the render function
{moreMenuOpen && (
<div className="more-dropdown">
<ul>
<button
type="button"
className="btn more-dropdown-button btn-light">
Button
</button>
</ul>
</div>
)}
// Child Component
<button onClick={() => functionNotBeingCalled()}>
Child Button
</button>
Any help in solving this problem would be appreciated, thank you.
Solution 1:[1]
Mousedown event is triggered before the onClick event so it will trigger first hence your menu will be closed and the onClick event won't be fired. As a workaround you can wrap you setState to close the menu on a setTimeout function to not close the menu immediately and actually fire the onClick event. Not the cleanest solution though.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Caio Nakai |
