Hook that detects outside presses and Escape to dismiss popovers
A filters popover opens from a “Filters” button. It should close when the user presses outside it or presses Escape. Two details make this harder than one contains check: pressing the trigger button itself must not count as outside (the button toggles the popover on its own, and closing first would reopen it immediately), and an Escape that a nested control already handled (for example, an open date picker inside the popover) must not also close the popover. Implement a React hook, useDismiss, that reports these dismiss gestures.
function useDismiss(
refs: Array<{ current: Element | null }>,
onDismiss: (reason: 'outside' | 'escape', event: Event) => void,
enabled?: boolean,
): void
refs: ref objects for every element that counts as “inside”, for example [triggerRef, popoverRef].enabled: defaults to true. Pass the popover’s open state so nothing listens while it is closed.document for pointerdown in the capture phase, so a press still counts when an element stops propagation.pointerdown whose target is not inside any of the elements (the element itself or one of its descendants) calls onDismiss('outside', event). A press inside any of them does nothing.current is null. Read ref.current when the event happens, not when subscribing, so elements that mount later are included.document for keydown in the normal (bubble) phase. event.key === 'Escape' calls onDismiss('escape', event), unless event.defaultPrevented is true (another handler already used that Escape). Other keys do nothing.enabled is false, attach no listeners. On unmount, remove both listeners.function FiltersMenu() {
const [open, setOpen] = useState(false);
const triggerRef = useRef(null);
const popoverRef = useRef(null);
useDismiss([triggerRef, popoverRef], () => setOpen(false), open);
return (
<>
<button ref={triggerRef} onClick={() => setOpen((o) => !o)}>Filters</button>
{open && (
<div ref={popoverRef}>
<label>Color <input /></label>
</div>
)}
</>
);
}
// open, press on the page background -> onDismiss('outside', event)
// open, press on the color input -> nothing (inside the popover)
// open, press on the Filters button -> nothing (inside the trigger); its onClick closes it
// open, Escape -> onDismiss('escape', event)
// open, Escape already prevented by a nested date picker -> nothing
// closed (enabled false) -> no listeners at all
pointerdown and keydown events on elements in the page.pointerdown and keydown listeners added to and removed from document. Re-renders happen inside ReactDOM.flushSync.Object.assign(window, { useDismiss }); below “Do not edit below this line”. The tests use it to call your hook.