Skip to content

Instantly share code, notes, and snippets.

@leofab86
Created May 20, 2019 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leofab86/5d91087fbeaca3963b9624170a4da1c9 to your computer and use it in GitHub Desktop.
Save leofab86/5d91087fbeaca3963b9624170a4da1c9 to your computer and use it in GitHub Desktop.
export function useClickOutside ({container, handler, dependencies, addListenerConditional = true}) {
useEffect(() => {
if(addListenerConditional) {
document.addEventListener('mousedown', handleClickOutside);
}
return () => document.removeEventListener('mousedown', handleClickOutside)
}, dependencies);
function handleClickOutside (e) {
if(!container.current.contains(e.target)) {
handler()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment