Skip to content

Instantly share code, notes, and snippets.

@hamzakaya
Created October 28, 2021 11:18
Show Gist options
  • Save hamzakaya/86c80c321de4079b0fb99e0f29d7616f to your computer and use it in GitHub Desktop.
Save hamzakaya/86c80c321de4079b0fb99e0f29d7616f to your computer and use it in GitHub Desktop.
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