Skip to content

Instantly share code, notes, and snippets.

@alii
Created February 17, 2021 21:02
Show Gist options
  • Save alii/5d7850a7db4141be455098f163873b7d to your computer and use it in GitHub Desktop.
Save alii/5d7850a7db4141be455098f163873b7d to your computer and use it in GitHub Desktop.
/**
* Handle clicks outside of an element.
* This is useful for closing a modal by clicking outside of the modal.
* @param callback - The callback function to run when clicking outside of an element
*/
export function useOutsideClick<E extends HTMLElement = HTMLElement>(callback: () => unknown) {
const container = useRef<E | null>(null);
useEffect(() => {
const handler = (event: MouseEvent) => {
if (!container.current) return;
if (!container.current.contains(event.target as HTMLElement)) {
callback();
}
};
document.addEventListener("click", handler);
return () => void document.removeEventListener("click", handler);
}, []);
return container;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment