Created
October 31, 2019 09:01
-
-
Save suhodolskiy/8e164d1bb27543ad1079f64d0bb83049 to your computer and use it in GitHub Desktop.
React Hook: Click Away
This file contains 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
function useClickAway(callback) { | |
const savedCallback = useRef() | |
const ref = createRef() | |
function handleClickOutside(event) { | |
if (ref && ref.current && !ref.current.contains(event.target)) { | |
savedCallback.current() | |
} | |
} | |
useEffect( | |
() => { | |
savedCallback.current = callback | |
}, | |
[callback] | |
) | |
useEffect(() => { | |
document.addEventListener('mousedown', handleClickOutside) | |
return () => document.removeEventListener('mousedown', handleClickOutside) | |
}) | |
return ref | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use: