usePopover

A lifecycle management hook for popover UI elements that handles visibility and "click-outside" logic.

Note

This hook provides a "Click Outside" and "Escape Key" listener out of the box. Ensure that both the anchorRef and popoverRef are correctly assigned to avoid the popover closing immediately when clicking the trigger.

Installation

bash

Description

The usePopover manages the open/closed state of an overlay anchored to a trigger element. It handles common accessibility and UX patterns, such as closing the popover when the user presses the Escape key or clicks outside the boundaries of both the popover content and the anchor (trigger) element.

Return values

NameTypeDescription
anchorRefReact.RefObject<T>Ref to be assigned to the trigger element (e.g., a button).
popoverRefReact.RefObject<T>Ref to be assigned to the floating content element.
isOpenbooleanReactive state indicating if the popover is currently visible.
open() => voidFunction to set isOpen to true.
close() => voidFunction to set isOpen to false.
toggle() => voidFunction to flip the current visibility state.

Demo

Popover

Source code

tsx