Matix200 of Strugini Crew
5/13/2020 - 4:06 PM

useOutsideAlerter

click outside html element to callback alert

import { useEffect } from "react";

function useOutsideAlerter(
  ref: React.RefObject<HTMLElement>,
  isOpen: boolean,
  callback: () => void
) {
  useEffect(() => {
    const handleClick = (e: MouseEvent) => {
      if (ref && ref.current && !ref.current.contains(e.target as Node)) {
        if (isOpen) {
          callback();
        }
      }
    };
    document.addEventListener("mousedown", handleClick);
    return () => {
      document.removeEventListener("mousedown", handleClick);
    };
  }, [ref, callback, isOpen]);
}

export default useOutsideAlerter;