Created
March 30, 2021 10:15
-
-
Save zheeeng/50af56c43b15ea846df47a105e001530 to your computer and use it in GitHub Desktop.
Revisions
-
zheeeng created this gist
Mar 30, 2021 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,29 @@ import { useEffect, useRef } from 'react' export const useClickOutside = <T extends HTMLElement>(callback: (event: MouseEvent) => void) => { const ref = useRef<T>(null) const eventRef = useRef(callback) useEffect( () => { eventRef.current = callback }, [callback] ) useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (event.target && ref.current && !ref.current.contains(event.target as Node)) { eventRef.current(event) } } document.addEventListener('mousedown', handleClickOutside); return () => { document.removeEventListener('mousedown', handleClickOutside); }; }, []); return ref }