Created
February 23, 2023 10:48
-
-
Save stavros-melidoniotis/d4b50b0a19bd21411fb168b7ba3e11af to your computer and use it in GitHub Desktop.
React hook for detecting clicks outside of an element
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 { RefObject, useEffect } from 'react' | |
const useClickOutside = (ref: RefObject<any>, callback: Function) => { | |
useEffect(() => { | |
const listener = (e: MouseEvent | TouchEvent) => { | |
if (!ref.current || ref.current.contains(e.target)) { | |
return | |
} | |
callback(e) | |
} | |
document.addEventListener('mousedown', listener) | |
document.addEventListener('touchstart', listener) | |
return () => { | |
document.removeEventListener('mousedown', listener) | |
document.removeEventListener('touchstart', listener) | |
} | |
}, [ref, callback]) | |
} | |
export default useClickOutside |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment