Skip to content

Instantly share code, notes, and snippets.

@stavros-melidoniotis
Created February 23, 2023 10:48
Show Gist options
  • Save stavros-melidoniotis/d4b50b0a19bd21411fb168b7ba3e11af to your computer and use it in GitHub Desktop.
Save stavros-melidoniotis/d4b50b0a19bd21411fb168b7ba3e11af to your computer and use it in GitHub Desktop.
React hook for detecting clicks outside of an element
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