Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | 1x 1x 259x 259x 259x 259x 259x 259x 259x 259x 259x 121x 28x 7x 7x 11x 7x 7x 4x 7x 28x 28x 259x 259x | import { useEffect, useRef } from 'react';
type RefLike = React.RefObject<HTMLElement | null>;
interface UseDismissOnOutsideClickOptions {
enabled: boolean;
ignoreRefs: RefLike[];
onDismiss: () => void;
}
/**
* Closes an open overlay on mousedown outside every ref in `ignoreRefs`.
* `ignoreRefs`/`onDismiss` are read from a ref internally, so callers can
* pass inline arrays/callbacks without re-subscribing on every render.
*/
export const useDismissOnOutsideClick = ({
enabled,
ignoreRefs,
onDismiss,
}: UseDismissOnOutsideClickOptions) => {
const ignoreRefsRef = useRef(ignoreRefs);
ignoreRefsRef.current = ignoreRefs;
const onDismissRef = useRef(onDismiss);
onDismissRef.current = onDismiss;
useEffect(() => {
if (!enabled) return;
const handleDismissClick = (event: MouseEvent) => {
const target = event.target as Node;
const isInsideIgnored = ignoreRefsRef.current.some((ref) =>
ref.current?.contains(target),
);
if (isInsideIgnored) return;
onDismissRef.current();
};
document.addEventListener('mousedown', handleDismissClick);
return () => document.removeEventListener('mousedown', handleDismissClick);
}, [enabled]);
};
|