Skip to content

Instantly share code, notes, and snippets.

@osmanmesutozcan
Created February 13, 2021 14:35
Show Gist options
  • Save osmanmesutozcan/591ad67fcf6cde80be7db213523e8fab to your computer and use it in GitHub Desktop.
Save osmanmesutozcan/591ad67fcf6cde80be7db213523e8fab to your computer and use it in GitHub Desktop.
/**
* Register a callback to trigger when we detect a click outside of refs.
*/
export function useDetectClickOutside(refs, callback) {
useEffect(() => {
const handleMouseDown = (e) => {
const clickOutsideOfRefs =
refs.every((r) => r.current) &&
refs.every((r) => !r.current.contains(e.target));
if (clickOutsideOfRefs) {
callback();
}
};
document.addEventListener("mousedown", handleMouseDown);
return () => document.removeEventListener("mousedown", handleMouseDown);
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment