buttery-components-logo
buttery.tools

usePopover

A hook that turns a button and any DOM node into a fully accessible popover using the Popover API.

This hook is great for easily launching a floating panel next to a focusable element.

Usages

The usePopover hook is the simplest hook to create an imperatively managed popover.

This hook uses RefCallbacks to apply the properties needed to the target and popover nodes. It then returns controls used to mange the visibility of the popover. The popover node always exists in the DOM and is not conditionally rendered based upon the state of the popover. This in turn, makes the usePopover hook a drop in React equiavalent to the declarative HTML mechanisms of popover & popovertarget.

The hook abstracts away acessibility and management to provide a nice and simple API to open, close and toggle your popovers.

You can read more about the usages of the Popover API by reading the MDN documentation.

NOTE It's important to mention that all elements managed using the usePopover hook are non-modal. This means that the rest of the page can be interacted with while the popover is open. If you're looking for a modal experience where the page is blocked, refer to the useModalDialog hook or the <Modal /> or <Drawer /> components.

This hook can be used alone or it can be used to create other more dynamic popover elements like useDropdown.

The usePopover hook is also the lowest primitive hook that is used to support more complicated popover hooks such as useDropdown.

Why not use popovertarget?

There are a few reasons why using the popover APIS native HTML attributes doesn't fully satisfy our needs here.

  1. Imperative vs. Declarative - The hook creates and manages a popover imperatively so it can be managed via callbacks, promises, etc... launched by user actions.
  2. Accessibility - This hook uses ref callbacks to set the proper controls needed to describe how the button interacts with the popover.
  3. Animations - The hook uses some standard JS interfaces to easily await the conclusion of any animations attached to the popoverNode. This makes it way eaiser to define CSS animations that add character to your elements.

Installation

# yarn
yarn add @buttery/components

# npm
npm install @buttery/components

Styling

CSS-in-JS

Style Objects

Examples

Barebones

Adding keyboard functionality

APIs

usePopover