Skip to content

Instantly share code, notes, and snippets.

@staydecent
Created May 11, 2020 22:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save staydecent/d8f9ab4f34347e87f87379da819e928a to your computer and use it in GitHub Desktop.
Save staydecent/d8f9ab4f34347e87f87379da819e928a to your computer and use it in GitHub Desktop.
import { useEffect } from 'react'
export function useDocumentClick (ref, cb) {
useEffect(() => {
const callback = (ev) => {
cb && cb(ref.current && !ref.current.contains(ev.target))
}
document.addEventListener('mousedown', callback)
document.addEventListener('touchstart', callback)
return () => {
document.removeEventListener('mousedown', callback)
document.removeEventListener('touchstart', callback)
}
}, [ref.current])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment