Skip to content

Instantly share code, notes, and snippets.

@vaporwavie
Created April 17, 2022 03:55
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 vaporwavie/2c520a187ba8a4ae8d807194f4f1812e to your computer and use it in GitHub Desktop.
Save vaporwavie/2c520a187ba8a4ae8d807194f4f1812e to your computer and use it in GitHub Desktop.
Use click outside custom hook used on VFR
import { useEffect } from 'react'
type ElementRef = null | {
current: HTMLElement | null
}
function useClickOutside(ref: ElementRef, handler: any) {
useEffect(() => {
const listener = (event: any) => {
if (!ref!.current || ref!.current.contains(event.target)) {
return
}
handler(event)
}
document.addEventListener('mousedown', listener, { passive: true })
document.addEventListener('touchstart', listener, { passive: true })
return () => {
document.removeEventListener('mousedown', listener)
document.removeEventListener('touchstart', listener)
}
}, [ref, handler])
}
export default useClickOutside
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment