Skip to content
Browse documentation

A small panel that belongs to a button: it rises off the trigger from the nearest point, flips to fit, and hands focus to what is inside.

Used forQuick editsShare settingsFiltersDetails on demand

Install with the shadcn CLI

$ npx shadcn@latest add @hairline/popover

Older shadcn CLI, or a network that blocks ui.shadcn.com? Install by URL: shadcn add https://hairlineui.com/r/popover.json. More

Templates

Need the whole page?

65 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 8 are free.

Where it’s used

  • Quick edits

    Rename a file or set a due date without leaving the list.

  • Share settings

    A link with access options under a Share button.

  • Filters

    A few fields behind a Filter button.

  • Details on demand

    More about a plan, a user or a status.

What it handles for you

Positioning, focus handover, Escape and outside presses are where most popovers go wrong; this one does all four.

Instead of wiring upRadix Popoverfloating-uifocus management
  1. From the trigger

    transform-origin is the point on the trigger nearest the panel.

  2. Stays in view

    Flips sides and shifts; follows scroll and resize.

  3. Focus handover

    In to the first field, back to the trigger on Escape.

  4. Close from inside

    children can be a function that receives close().

Overview

Popovers often appear from nowhere, cover their trigger and leave focus behind. This one rises off its trigger from the point nearest to it, flips and shifts to stay in the window, moves focus to the first field inside, and on Escape gives focus back to the trigger. For a list of actions, use the dropdown menu.

States

open
Rises 6px from its side, out of a 4px blur, from 0.96 (320ms).
inside
Focus on the first field or the panel.
close
Escape returns focus to the trigger; a press outside just closes (180ms).

Usage

usage.tsx
import { Popover } from "@/components/popover";<Popover label="Rename" trigger={<button>Rename</button>}>  {({ close }) => <form onSubmit={(e) => { e.preventDefault(); save(); close(); }}>…</form>}</Popover>

Depends on lucide-react, installed for you by the CLI along with the keyframes it needs.

Props

trigger
ReactElement
The button; it gets aria-expanded and the click.
children
ReactNode | ({ close }) => ReactNode
The content.
side / align= "bottom" / "center"
Side / Align
Where it sits.
open / onOpenChange
boolean / (open) => void
Control it.
width= 280
number
Panel width.
label
string
Accessible name of the panel.

Accessibility and motion

  • Placement, presence and dismissal live in floating.ts, shared by tooltip, popover, dropdown and context menus: they all flip, shift, enter and leave the same way.
  • The panel is role="dialog"; the trigger gets aria-haspopup and aria-expanded.
  • Reduced motion: it fades.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

Source

"use client";import * as React from "react";import { createPortal } from "react-dom";import { enterStyle, themeVars, useDismiss, useFloating, usePresence, type Align, type Side } from "./floating";import { useInteractionReducedMotion } from "./ui-interaction-motion";/* ───────────────────────────────────────────────────────── * POPOVER: a small panel that belongs to a button * *   open     the panel rises off its trigger out of a blur, from *            the point on the trigger nearest to it, and flips *            or shifts to stay in the window *   inside   focus moves to the first field in it (or the panel) *   close    Escape returns focus to the trigger; a press *            outside just closes; `close()` from inside too * * For a list of actions use DropdownMenu; this is for content * (a short form, a colour picker, details). * ───────────────────────────────────────────────────────── */export interface PopoverProps {  trigger: React.ReactElement<React.HTMLAttributes<HTMLElement>>;  /** The content, or a function that gets `close`. */  children: React.ReactNode | ((api: { close: () => void }) => React.ReactNode);  side?: Side;  align?: Align;  open?: boolean;  onOpenChange?: (open: boolean) => void;  /** Width of the panel in px. */  width?: number;  /** Accessible name of the panel. */  label?: string;  className?: string;}const FOCUSABLE = 'input, textarea, select, button, [href], [tabindex]:not([tabindex="-1"])';export function Popover({ trigger, children, side = "bottom", align = "center", open: controlled, onOpenChange, width = 280, label, className = "" }: PopoverProps) {  const reduced = useInteractionReducedMotion();  const anchor = React.useRef<HTMLSpanElement>(null);  const surface = React.useRef<HTMLDivElement>(null);  const [own, setOwn] = React.useState(false);  const open = controlled ?? own;  const { mounted, shown } = usePresence(open, 180);  const place = useFloating({ open: mounted, anchor, floating: surface, side, align, offset: 8 });  const [vars, setVars] = React.useState<React.CSSProperties>({});  const id = React.useId();  const triggerId = React.useId();  const setOpen = (next: boolean, refocus = false) => {    if (controlled === undefined) setOwn(next);    onOpenChange?.(next);    // By id rather than a ref: this runs from handlers that are created while rendering.    if (!next && refocus) document.getElementById(trigger.props.id ?? triggerId)?.focus();  };  useDismiss(open, (reason) => setOpen(false, reason === "escape"), [anchor, surface]);  React.useLayoutEffect(() => {    if (mounted) setVars(themeVars(anchor.current));  }, [mounted]);  React.useEffect(() => {    if (!open || !place.ready) return;    const el = surface.current;    (el?.querySelector<HTMLElement>(FOCUSABLE) ?? el)?.focus({ preventScroll: true });  }, [open, place.ready]);  const close = () => setOpen(false, true);  return (    <>      <span ref={anchor} className="inline-flex">        {React.cloneElement(trigger, {          id: trigger.props.id ?? triggerId,          "aria-haspopup": "dialog",          "aria-expanded": open,          "aria-controls": open ? id : undefined,          onClick: (e: React.MouseEvent<HTMLElement>) => {            trigger.props.onClick?.(e);            setOpen(!open);          },        })}      </span>      {mounted &&        createPortal(          <div            ref={surface}            id={id}            role="dialog"            aria-label={label}            tabIndex={-1}            className={`fixed left-0 top-0 z-[55] max-w-[calc(100vw_-_16px)] rounded-[16px] bg-popover p-4 text-[13.5px] text-popover-foreground shadow-[0_0_0_1px_var(--border)] outline-none ${className}`}            style={{ ...vars, width, left: place.x, top: place.y, transformOrigin: place.origin, ...enterStyle(shown, place.side, reduced) }}          >            {typeof children === "function" ? children({ close }) : children}          </div>,          document.body,        )}    </>  );}export default Popover;

Registry item: /r/popover.json