24 lines
657 B
TypeScript
24 lines
657 B
TypeScript
"use client";
|
|
|
|
import { useEffect, type RefObject } from "react";
|
|
|
|
export function useClickOutside(
|
|
refs: Array<RefObject<HTMLElement | null>>,
|
|
onOutside: () => void,
|
|
enabled: boolean,
|
|
) {
|
|
useEffect(() => {
|
|
if (!enabled) return;
|
|
|
|
const onPointerDown = (e: PointerEvent) => {
|
|
const target = e.target as Node | null;
|
|
if (!target) return;
|
|
|
|
const clickedInside = refs.some((r) => r.current?.contains(target));
|
|
if (!clickedInside) onOutside();
|
|
};
|
|
|
|
window.addEventListener("pointerdown", onPointerDown);
|
|
return () => window.removeEventListener("pointerdown", onPointerDown);
|
|
}, [enabled, onOutside, refs]);
|
|
}
|