Skip to content

Instantly share code, notes, and snippets.

@schmidt1024
Created April 14, 2021 14:42
Show Gist options
  • Save schmidt1024/7561e9c9e8af2886f50c0f5aa1905c88 to your computer and use it in GitHub Desktop.
Save schmidt1024/7561e9c9e8af2886f50c0f5aa1905c88 to your computer and use it in GitHub Desktop.
custom react hook - when clicking outside of an element -> do something
function useClickOutside(elRef, callback) {
const callbackRef = React.useRef()
callbackRef.current = callback
React.useEffect(() => {
const handleClickOutside = e => {
if (elRef?.current?.contains(e.target) && callbackRef.current) {
callbackRef.current(e)
}
}
document.addEventListiner('click', handleClickOutside, true)
return () => {
document.removeEventListiner('click', handleClickOutside, true)
}
}, [callbackRef, elRef])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment