這個是我在第一份工作時學到的,非常方便,尤其是在dropdown、popup、modal等常常使用,可以讓你點擊空白區域關閉,會回傳一個ref讓你可以放在component上
import { useEffect, useRef } from "react";
const useOutsideClick = (callback: () => void) => {
const ref = useRef<HTMLElement | null>(null);
useEffect(() => {
const handleClick = (event: MouseEvent) => {
if (ref.current && !ref.current.contains(event.target as Node)) {
callback();
}
};
document.addEventListener("click", handleClick);
return () => {
document.removeEventListener("click", handleClick);
};
}, [callback]); // updated dependency array to include callback instead of ref
return ref;
};
export default useOutsideClick;