Created
February 8, 2021 14:39
-
-
Save unigazer/649b11e17067909c6f1ae4723b654d85 to your computer and use it in GitHub Desktop.
Click outside React with hooks
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
import useOutsideClick from './useOutsideClick'; | |
export default () => { | |
useOutsideClick(useRef, () => { | |
// Update state or whatever | |
}) | |
return <></> | |
} |
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
import { useEffect } from 'react'; | |
const useOutsideClick = (ref, cb) => { | |
const handleClick = (e) => { | |
if (ref.current && !ref.current.contains(e.target)) { | |
cb(); | |
} | |
} | |
useEffect(() => { | |
document.addEventListener('click', handleClick); | |
return () => { | |
document.removeEventListener('click', handleClick); | |
} | |
}); | |
} | |
export default useOutsideClick; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment