Last active
January 17, 2020 10:21
-
-
Save NikaBuligini/66a2ec0a5d51a594b95f3603c0097c34 to your computer and use it in GitHub Desktop.
useClickOutside hook for react
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
import React from 'react'; | |
export function useEventListener(eventName, handler, element = document) { | |
const savedCallback = React.useRef(); | |
React.useEffect(() => { | |
savedCallback.current = handler; | |
}, [handler]); | |
React.useEffect(() => { | |
// Make sure element supports addEventListener | |
const isSupported = element && element.addEventListener; | |
if (!isSupported) { | |
return; | |
} | |
const eventListener = event => savedCallback.current(event); | |
element.addEventListener(eventName, eventListener); | |
return () => { | |
element.removeEventListener(eventName, eventListener); | |
}; | |
}, [eventName, element]); | |
} | |
export function useClickOutside(callback) { | |
const ref = React.useRef(null); | |
const mousedown = event => { | |
if (ref.current && !ref.current.contains(event.target)) { | |
callback(event); | |
} | |
}; | |
useEventListener('mousedown', mousedown); | |
return ref; | |
} | |
// usage | |
const Example = ({ children }) => { | |
const ref = useClickOutside(() => { | |
console.log('clicked'); | |
}); | |
return <div ref={ref}>{children}</div>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment