Skip to content

Instantly share code, notes, and snippets.

@SubZane
Created June 14, 2023 08:33
Show Gist options
  • Save SubZane/2ec16e2beebb2fe04cb5b722073c55c3 to your computer and use it in GitHub Desktop.
Save SubZane/2ec16e2beebb2fe04cb5b722073c55c3 to your computer and use it in GitHub Desktop.
import { useEffect, useRef } from 'react'
export const useOutsideClick = (callback: () => void) => {
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (ref.current && !ref.current.contains(event.target as Node)) {
callback()
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => {
document.removeEventListener('mousedown', handleClickOutside)
}
}, [callback])
return ref
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment