Last active
July 22, 2019 13:50
-
-
Save AlpacaGoesCrazy/18cf582096245507a3fceadbecf0c669 to your computer and use it in GitHub Desktop.
React hook and HOC for handling clicks outside your component
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
/* Hook for handling click outside your react component */ | |
const useOutsideClick = (onOutsideClick) => { | |
const elementRef = useRef(null) | |
useEffect(() => { | |
const handleOutsideClick = (e) => { | |
if(typeof onOutsideClick === 'function' && !elementRef.current.contains(e.target)) { | |
onOutsideClick(e) | |
} | |
} | |
document.addEventListener('mousedown', handleOutsideClick, false) | |
return () => { | |
document.removeEventListener('mousedown', handleOutsideClick, false) | |
} | |
}) | |
return [elementRef] | |
} | |
/* Example */ | |
const App = props => { | |
const [wrapRef] = outsideClickHook(() => console.log('clicked outside!')) | |
return( | |
<div ref={wrapRef}> | |
<MyComponent/> | |
</div> | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment