Skip to content

Instantly share code, notes, and snippets.

@zheeeng
Created March 30, 2021 10:15
Show Gist options
  • Save zheeeng/50af56c43b15ea846df47a105e001530 to your computer and use it in GitHub Desktop.
Save zheeeng/50af56c43b15ea846df47a105e001530 to your computer and use it in GitHub Desktop.
useClickOutside.tsx
import { useEffect, useRef } from 'react'
export const useClickOutside = <T extends HTMLElement>(callback: (event: MouseEvent) => void) => {
const ref = useRef<T>(null)
const eventRef = useRef(callback)
useEffect(
() => {
eventRef.current = callback
},
[callback]
)
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (event.target && ref.current && !ref.current.contains(event.target as Node)) {
eventRef.current(event)
}
}
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, []);
return ref
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment