Dwinzo_dev/app/src/utils/outerClick.ts

34 lines
1.1 KiB
TypeScript

import React from "react";
interface OuterClickProps {
contextClassName: string[]; // Make sure this is an array of strings
setMenuVisible: React.Dispatch<React.SetStateAction<boolean>>;
}
export default function OuterClick({
contextClassName,
setMenuVisible,
}: OuterClickProps) {
const handleClick = (event: MouseEvent) => {
const targets = event.target as HTMLElement;
// Check if the click is outside of any of the provided class names
const isOutside = contextClassName.every(
(className) => !targets.closest(`.${className}`)
);
if (isOutside) {
setMenuVisible(false); // Close the menu by updating the state
}
};
// Add event listener on mount and remove it on unmount
React.useEffect(() => {
document.addEventListener("click", handleClick);
return () => {
document.removeEventListener("click", handleClick);
};
}, [contextClassName]); // Add contextClassName to dependency array to handle any changes
return null; // This component doesn't render anything
}