Skip to content

Instantly share code, notes, and snippets.

@kwiss
Created August 18, 2019 11:44
Show Gist options
  • Save kwiss/a8cf1e772347217297463fb5b8a3cd49 to your computer and use it in GitHub Desktop.
Save kwiss/a8cf1e772347217297463fb5b8a3cd49 to your computer and use it in GitHub Desktop.
React hook to click outside a ref
// Hook
function useOnClickOutside(ref, handler) {
useEffect(() => {
const listener = event => {
if (!ref.current || ref.current.contains(event.target)) {
return;
}
handler(event);
};
document.addEventListener("mousedown", listener);
document.addEventListener("touchstart", listener);
return () => {
document.removeEventListener("mousedown", listener);
document.removeEventListener("touchstart", listener);
};
}, [ref, handler]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment