2023-11-24 07:43:45 +00:00
|
|
|
/* eslint-disable react-hooks/exhaustive-deps */
|
2023-11-23 15:25:24 +00:00
|
|
|
import { useEffect } from "react";
|
|
|
|
|
|
|
|
export const useClickOutside = (
|
|
|
|
ref: { current: HTMLElement },
|
|
|
|
handler: () => void,
|
2023-11-24 07:43:45 +00:00
|
|
|
...deps: unknown[]
|
2023-11-23 15:25:24 +00:00
|
|
|
) => {
|
|
|
|
useEffect(() => {
|
2023-11-24 07:43:45 +00:00
|
|
|
const handleClickOutside = (e: MouseEvent) => {
|
2023-11-23 15:25:24 +00:00
|
|
|
e.stopPropagation();
|
2023-11-24 07:43:45 +00:00
|
|
|
const target = e.target as HTMLElement;
|
|
|
|
if (ref.current && !ref.current.contains(target)) handler();
|
2023-11-23 15:25:24 +00:00
|
|
|
};
|
|
|
|
document.addEventListener("mousedown", handleClickOutside);
|
|
|
|
return () => {
|
|
|
|
document.removeEventListener("mousedown", handleClickOutside);
|
|
|
|
};
|
2023-11-24 07:43:45 +00:00
|
|
|
}, [ref, handler, ...deps]);
|
2023-11-23 15:25:24 +00:00
|
|
|
};
|