Created
April 14, 2021 14:42
-
-
Save cod3cow/7561e9c9e8af2886f50c0f5aa1905c88 to your computer and use it in GitHub Desktop.
custom react hook - when clicking outside of an element -> do something
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
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