Created
October 28, 2021 11:18
-
-
Save hamzakaya/86c80c321de4079b0fb99e0f29d7616f 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'; | |
const DEFAULT_EVENTS = ['mousedown', 'touchstart']; | |
export function useClickOutside<T extends HTMLElement = any>( | |
handler: () => void, | |
events?: string[] | null, | |
nodes?: HTMLElement[] | |
) { | |
const ref = useRef<T>(); | |
useEffect(() => { | |
const listener = (event: any) => { | |
if (Array.isArray(nodes)) { | |
const shouldTrigger = nodes.every((node) => !!node && !node.contains(event.target)); | |
shouldTrigger && handler(); | |
} else if (ref.current && !ref.current.contains(event.target)) { | |
handler(); | |
} | |
}; | |
(events || DEFAULT_EVENTS).forEach((fn) => document.addEventListener(fn, listener)); | |
return () => { | |
(events || DEFAULT_EVENTS).forEach((fn) => document.removeEventListener(fn, listener)); | |
}; | |
}, [ref, handler, nodes]); | |
return ref; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment