Last active
December 30, 2021 20:12
-
-
Save codemile/19ab6c74adca21344b337d18d7edc002 to your computer and use it in GitHub Desktop.
Hook that adds a click listener outside of an element.
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
import {DependencyList, useCallback, useEffect, useRef} from 'react'; | |
export const useClickOutside = <T extends (...args: any[]) => any>( | |
cb: T, | |
dep: DependencyList | |
) => { | |
const ref = useRef<HTMLElement>(null); | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
const callback = useCallback(cb, dep); | |
useEffect(() => { | |
const listener = (e: MouseEvent) => { | |
if (!ref.current?.contains(e.target as Node)) { | |
callback(e); | |
} | |
}; | |
document.addEventListener('click', listener); | |
return () => document.removeEventListener('click', listener); | |
}, [ref, callback]); | |
return ref; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment