aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-on-click-outside.tsx
blob: b810ddc1bee74ee480c6be2b61ba4802d95b905c (plain)
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
43
44
45
46
47
48
49
50
import { RefObject, useCallback, useEffect, useRef } from 'react';

export type UseOnClickOutsideCallback = (target: Node) => void;

/**
 * Detect click/focus outside an element and fire a callback function.
 *
 * @param {UseOnClickOutsideCallback} callback - A callback function to fire.
 * @param {boolean} useCapture - Define event propagation method. Default: true.
 * @returns {RefObject} A React reference object.
 */
export const useOnClickOutside = <T extends HTMLElement>(
  callback: UseOnClickOutsideCallback,
  useCapture: boolean = true
): RefObject<T> => {
  const ref = useRef<T | null>(null);

  /**
   * Check if the target is outside the ref.
   *
   * @param {Node} target - The event target.
   * @returns {boolean | null} True if the target is outside the ref.
   */
  const isTargetOutside = (target: Node): boolean | null => {
    return ref.current && !ref.current.contains(target);
  };

  /**
   * Fire the callback if the event target is outside.
   */
  const handler = useCallback(
    (e: MouseEvent | FocusEvent) => {
      if (e.target && isTargetOutside(e.target as Node))
        callback(e.target as Node);
    },
    [callback]
  );

  useEffect(() => {
    document.addEventListener('click', handler, useCapture);
    document.addEventListener('focusin', handler, useCapture);

    return () => {
      document.removeEventListener('click', handler);
      document.removeEventListener('focusin', handler);
    };
  }, [handler, useCapture]);

  return ref;
};