Skip to content

Instantly share code, notes, and snippets.

@BrockHerion
Created December 14, 2021 17:00
Show Gist options
  • Save BrockHerion/27a5b4cf157e32595da4b57dd3044cd2 to your computer and use it in GitHub Desktop.
Save BrockHerion/27a5b4cf157e32595da4b57dd3044cd2 to your computer and use it in GitHub Desktop.
Close on click out
useEffect(() => {
const checkClickedOutside = (ev: MouseEvent) => {
console.log("Click");
if (
isDropdownOpen &&
ref.current &&
!ref.current.contains(ev.target as Node)
) {
setDropdownOpen(false);
}
};
document.addEventListener("mousedown", checkClickedOutside);
return () => {
document.removeEventListener("mousedown", checkClickedOutside, {
capture: true,
});
};
}, [isDropdownOpen]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment