2023-02-16 22:39:57 +00:00
|
|
|
import type React from "react";
|
|
|
|
import { useEffect } from "react";
|
2023-02-13 14:14:23 +00:00
|
|
|
|
|
|
|
export default function useOnClickOutside(
|
|
|
|
ref: React.RefObject<HTMLDivElement>,
|
|
|
|
handler: (e?: MouseEvent | TouchEvent) => void
|
|
|
|
) {
|
|
|
|
useEffect(() => {
|
|
|
|
const listener = (event: MouseEvent | TouchEvent) => {
|
|
|
|
if (!ref.current || ref.current.contains(event.target as Node)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
handler(event);
|
|
|
|
};
|
|
|
|
|
|
|
|
document.addEventListener("mousedown", listener);
|
|
|
|
document.addEventListener("touchstart", listener);
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
document.removeEventListener("mousedown", listener);
|
|
|
|
document.removeEventListener("touchstart", listener);
|
|
|
|
};
|
|
|
|
}, [ref, handler]);
|
|
|
|
}
|