Created
February 17, 2021 21:02
-
-
Save alii/5d7850a7db4141be455098f163873b7d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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