Skip to content

Instantly share code, notes, and snippets.

@worc
Created April 21, 2020 22:41
Show Gist options
  • Save worc/799c7d20189cecd715b2183d504751c6 to your computer and use it in GitHub Desktop.
Save worc/799c7d20189cecd715b2183d504751c6 to your computer and use it in GitHub Desktop.
ok, so i've definitely done custom hooks with a useState before
function clickAwayListener (elementId, callback) {
return event => {
const outsideClick = !document.getElementById(elementId).contains(event.target)
if (outsideClick) {
callback()
}
}
}
export function useClickAway (elementId, callback) {
const listener = clickAwayListener(elementId, callback)
useEffect(() => {
document.addEventListener('click', listener)
return () => document.removeEventListener('click', listener)
}, [])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment