Created
June 14, 2023 08:33
-
-
Save SubZane/2ec16e2beebb2fe04cb5b722073c55c3 to your computer and use it in GitHub Desktop.
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 { 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