I'm trying to mimic a header where if you click a dropdown menu, it will display the popup menu and upon clicking outside of the popup menu element, it'll disappear for multiple elements in the header.
Here's a vanilla pen that I modified but could not manage to get it working: https://codepen.io/anon/pen/JOGGzL
handleClick() {
if (!this.state.popupVisible) {
document.addEventListener('click', this.handleOutsideClick, false);
} else {
document.removeEventListener('click', this.handleOutsideClick, false);
}
this.setState(prevState => ({
popupVisible: !prevState.popupVisible,
}));
}
handleOutsideClick(e) {
if (this.node.contains(e.target)) {
return;
}
this.handleClick();
}
I've tried creating unique refs and passing in a parameter through handleClick and handleOutsideClick to differentiate between the two different popup buttons, but I'm running into an issue where it seems to be spawning a lot of EventListeners without removing them correctly.
What would be the most elegant way to toggle either one button at a time and deactivating all if the user clicks outside either popup elements? Would I have to create separate Components to handle this?
Thanks