Skip to content

Instantly share code, notes, and snippets.

@AlpacaGoesCrazy
Last active July 22, 2019 13:50
Show Gist options
  • Save AlpacaGoesCrazy/18cf582096245507a3fceadbecf0c669 to your computer and use it in GitHub Desktop.
Save AlpacaGoesCrazy/18cf582096245507a3fceadbecf0c669 to your computer and use it in GitHub Desktop.
React hook and HOC for handling clicks outside your component
/* 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