Skip to content

Instantly share code, notes, and snippets.

@ilxanlar
Created June 12, 2021 07:43
Show Gist options
  • Save ilxanlar/af01d9e8c9268f7ed1520310e7ca8350 to your computer and use it in GitHub Desktop.
Save ilxanlar/af01d9e8c9268f7ed1520310e7ca8350 to your computer and use it in GitHub Desktop.
import { useEffect } from 'react'
export default function useOnClickOutside(ref, callback) {
useEffect(() => {
const listener = (event) => {
if (ref && ref.current && !ref.current.contains(event.target)) {
callback(event)
}
}
document.addEventListener('mousedown', listener)
document.addEventListener('touchstart', listener)
return () => {
document.removeEventListener('mousedown', listener)
document.removeEventListener('touchstart', listener)
}
}, [ref, callback])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment