File size: 1,111 Bytes
f0743f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { useEffect, RefObject } from 'react';
type Handler = () => void;

export default function useOnClickOutside(
  ref: RefObject<HTMLElement>,
  handler: Handler,
  excludeIds: string[],
  customCondition?: (target: EventTarget | Element | null) => boolean,
): void {
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Node | null;

      if (target && 'id' in target && excludeIds.includes((target as HTMLElement).id)) {
        return;
      }

      if (
        target?.parentNode &&
        'id' in target.parentNode &&
        excludeIds.includes((target.parentNode as HTMLElement).id)
      ) {
        return;
      }

      if (customCondition && customCondition(target)) {
        return;
      }

      if (ref.current && !ref.current.contains(target)) {
        handler();
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ref, handler]);
}