detect click outside element react typescript
function useOnClickOutside<T extends HTMLElement = HTMLElement>(
ref: RefObject<T>,
handler: (event: MouseEvent) => void
): void {
useEffect(() => {
const listener = (event: MouseEvent) => {
const el = ref?.current;
// Do nothing if clicking ref's element or descendent elements
if (!el || el.contains(event.target as Node)) {
return;
}
handler(event);
};
document.addEventListener(`mousedown`, listener);
return () => {
document.removeEventListener(`mousedown`, listener);
};
// Reload only if ref or handler changes
}, [ref, handler]);
}
// Usage example, code below will not work if you just copy and paste
const MyComponent = (): JSX.Element => {
const [show, setShow] = useState(false);
const ref = useRef(null);
const handleClickOutside = () => {
// Your custom logic here
console.log("clicked outside");
};
useOnClickOutside(ref, handleClickOutside);
return (
<>
<button
onClick={() => {
setShow(!show);
}}
>
Columns
</button>
{show ? (
<section ref={ref}
<OtherComponentThatYouWantToShow />
</section>
) : (
<></>
)}
</>
);
};