Menu

Components

Menu

A button that opens a list of actions, for the things you can do with one item.

Introduction

A menu keeps the actions of one thing (a file, a row, an account) behind one button: rename, duplicate, delete. Use it when there are too many actions for buttons, or when most of them are rarely used. To choose a value from a list use a Select, to search for a command a Command Menu, and for the menu that opens with a right click a Context Menu.

  • A button with text, or only an icon (the three dots of a row), and any other button can open it, including one that opens on a press and hold.
  • Items with an icon, a description and the keys, links, disabled and dangerous items, titled sections, checkable items (checkboxes and a choice of one), and submenus inside submenus.
  • The panel turns to the other side when there is no room, and can be at least as wide as the button.
  • Built on react-aria's Menu and Popover, so the arrow keys, typeahead, focus (into the menu, and back to the button when it closes) and the screen reader announcements come from there.

The keys shown in an item are only shown: the menu does not listen for them.

Installation

centerUI has no CLI or registry yet: components are copied into your project.

# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx

# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx

# npm
npm install react-aria-components tailwind-variants tailwind-merge clsx

Manual installation

The trigger is a Button, so copy that too. Copy these files into your project and keep the paths, or adjust the imports.

1. Add the styles

src/types/menu-styles.tsShow code
import { tv } from "tailwind-variants";

// Styles for Menu, and for ContextMenu, which has the same panel and items. `popover` gives the panel its small entrance animation
// (see globals.css).
export const menuStyles = tv({
  slots: {
    popover:
      "popover z-50 max-w-[calc(100vw-1rem)] min-w-52 overflow-y-auto rounded-xl border bg-card p-1 text-card-fg shadow-lg",
    menu: "flex flex-col outline-none",
    section: "flex flex-col [&:not(:first-child)]:mt-1",
    heading: "px-2.5 pt-1.5 pb-1 text-xs font-medium text-muted-fg",
    item: [
      "group/item flex cursor-default items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-sm outline-none select-none",
      "data-focused:bg-muted data-pressed:bg-muted/70 data-open:bg-muted",
      "data-disabled:cursor-not-allowed data-disabled:opacity-50",
      "data-[variant=danger]:text-danger data-[variant=danger]:data-focused:bg-danger/10",
    ],
    indicator:
      "flex size-4 shrink-0 items-center justify-center text-fg [&_svg]:size-4",
    description: "truncate text-xs font-normal text-muted-fg",
    text: "flex min-w-0 flex-1 flex-col",
    icon: "flex size-4 shrink-0 items-center justify-center text-muted-fg [&_svg]:size-4 group-data-[variant=danger]/item:text-current",
    label: "min-w-0 flex-1 truncate",
    shortcut:
      "ml-6 flex shrink-0 items-center gap-1 font-sans text-xs text-muted-fg",
    chevron: "ml-4 size-4 shrink-0 text-muted-fg",
    separator: "-mx-1 my-1 h-px border-0 bg-border",
  },
});

2. Add the Menu file

src/components/ui/menu/menu.tsxShow code
"use client";

import { type ReactNode, useId } from "react";
import {
  Menu as AriaMenu,
  MenuItem as AriaMenuItem,
  type MenuProps as AriaMenuProps,
  MenuSection as AriaMenuSection,
  MenuTrigger as AriaMenuTrigger,
  type MenuTriggerProps as AriaMenuTriggerProps,
  type PopoverProps as AriaPopoverProps,
  Header,
  Popover,
  Separator,
  SubmenuTrigger,
} from "react-aria-components";
import {
  CheckIcon,
  ChevronDownIcon,
  ChevronRightIcon,
} from "@/components/icons";
import { Button, type ButtonProps } from "@/components/ui/button/button";
import { cn } from "@/lib/cn";
import { menuStyles } from "@/types/menu-styles";

const styles = menuStyles();

export type MenuProps = AriaMenuTriggerProps;

/**
 * A menu: a button that opens a list of actions. Use it for the actions that
 * belong to one thing (a file, a row, an account) and would take too much room
 * as buttons: rename, duplicate, delete. For a list to choose one value from,
 * use a Select, and for one to search in, a Command Menu.
 *
 * Put a `MenuTrigger` (or any button) and a `MenuContent` with the items in it.
 * Built on react-aria's Menu and Popover, so the arrow keys, typeahead, submenus,
 * focus (into the menu, and back to the button when it closes) and the screen
 * reader announcements come from there.
 *
 * @example
 * <Menu>
 *   <MenuTrigger>Options</MenuTrigger>
 *   <MenuContent aria-label="Options">
 *     <MenuItem onAction={rename}>Rename</MenuItem>
 *     <MenuItem variant="danger" onAction={remove}>Delete</MenuItem>
 *   </MenuContent>
 * </Menu>
 */
export function Menu(props: MenuProps) {
  return <AriaMenuTrigger {...props} />;
}

export interface MenuTriggerProps extends Omit<ButtonProps, "children"> {
  /** What the button says. Without text, use `isIcon` and give it an `aria-label`. */
  children?: ReactNode;
  /** A small arrow at the end, that says the button opens something. Defaults to `true` for a button with text. */
  showChevron?: boolean;
}

/**
 * The button that opens a `Menu`. It is a `Button`, so it takes its variants and
 * sizes. It shows a small arrow unless it has only an icon.
 */
export function MenuTrigger({
  children,
  showChevron,
  isIcon,
  variant = "outline",
  ...props
}: MenuTriggerProps) {
  const chevron = showChevron ?? !isIcon;

  return (
    <Button variant={variant} isIcon={isIcon} {...props}>
      {children}
      {chevron ? <ChevronDownIcon aria-hidden="true" /> : null}
    </Button>
  );
}

export interface MenuContentProps
  extends Omit<
      AriaMenuProps<object>,
      "className" | "style" | "children" | "aria-label"
    >,
    Pick<
      AriaPopoverProps,
      "placement" | "offset" | "crossOffset" | "shouldFlip"
    > {
  /** `MenuItem`s, `MenuSection`s, `MenuSubmenu`s and `MenuSeparator`s. */
  children: ReactNode;
  /** Names the menu for screen readers, such as "File actions". */
  "aria-label"?: string;
  /** Make the panel at least as wide as the button. Defaults to `false`. */
  matchTriggerWidth?: boolean;
  className?: string;
}

/**
 * The panel of a `Menu`: it opens next to the button, and turns to the other
 * side when there is not room. Arrow keys move, a letter jumps to an item, Enter
 * runs it, and Escape closes it.
 */
export function MenuContent({
  children,
  "aria-label": ariaLabel = "Menu",
  placement = "bottom start",
  offset = 6,
  crossOffset,
  shouldFlip,
  matchTriggerWidth = false,
  className,
  ...props
}: MenuContentProps) {
  return (
    <Popover
      placement={placement}
      offset={offset}
      crossOffset={crossOffset}
      shouldFlip={shouldFlip}
      className={cn(
        styles.popover(),
        matchTriggerWidth && "min-w-(--trigger-width)",
        className,
      )}
    >
      <AriaMenu {...props} aria-label={ariaLabel} className={styles.menu()}>
        {children}
      </AriaMenu>
    </Popover>
  );
}

export interface MenuItemProps {
  /** What the item is called. */
  children: ReactNode;
  /** Runs when the item is chosen, by Enter or by a press. */
  onAction?: () => void;
  /** An icon before the name. */
  icon?: ReactNode;
  /** A second, smaller line under the name. */
  description?: ReactNode;
  /** The keys of the action, shown at the end of the row, such as `"⌘ C"`. They are only shown: the item does not listen for them. */
  shortcut?: string;
  /** Red, for an action that destroys something. */
  variant?: "default" | "danger";
  /** Makes it a link to this address instead of running a function. */
  href?: string;
  /** The text a typed letter is matched to and a screen reader says, when the name is not text. Defaults to the name. */
  textValue?: string;
  /** Close the menu after the item is chosen. Defaults to `true`, and to `false` for an item that can be checked. */
  closeOnAction?: boolean;
  isDisabled?: boolean;
  /** A stable name for it. Needed for an item in a section that can be checked, as it is what `selectedKeys` holds. */
  id?: string;
}

function ShortcutKeys({ shortcut }: { shortcut: string }) {
  // A span, not react-aria's Keyboard: that says the item has a shortcut of its
  // own to assistive technology, and these keys are only shown.
  return <span className={styles.shortcut()}>{shortcut}</span>;
}

/**
 * One action in the menu: a name, and if you like an icon and the keys. In a
 * `MenuSection` that can be checked, it shows a check while it is on.
 */
export function MenuItem({
  children,
  onAction,
  icon,
  description,
  shortcut,
  variant = "default",
  href,
  textValue,
  closeOnAction,
  isDisabled,
  id,
}: MenuItemProps) {
  // An item keeps one id for as long as it is there, even when its name changes.
  const generatedId = useId();

  return (
    <AriaMenuItem
      id={id ?? generatedId}
      href={href}
      isDisabled={isDisabled}
      textValue={
        textValue ?? (typeof children === "string" ? children : undefined)
      }
      shouldCloseOnSelect={closeOnAction}
      data-variant={variant}
      onAction={onAction}
      className={styles.item()}
    >
      {({ selectionMode, isSelected, hasSubmenu }) => (
        <>
          {selectionMode !== "none" ? (
            <span aria-hidden="true" className={styles.indicator()}>
              {isSelected ? (
                selectionMode === "single" ? (
                  <span className="size-1.5 rounded-full bg-current" />
                ) : (
                  <CheckIcon />
                )
              ) : null}
            </span>
          ) : null}
          {icon ? (
            <span aria-hidden="true" className={styles.icon()}>
              {icon}
            </span>
          ) : null}
          {description ? (
            <span className={styles.text()}>
              <span className={styles.label()}>{children}</span>
              <span className={styles.description()}>{description}</span>
            </span>
          ) : (
            <span className={styles.label()}>{children}</span>
          )}
          {shortcut ? <ShortcutKeys shortcut={shortcut} /> : null}
          {hasSubmenu ? (
            <ChevronRightIcon aria-hidden="true" className={styles.chevron()} />
          ) : null}
        </>
      )}
    </AriaMenuItem>
  );
}

export interface MenuSectionProps {
  /** The title of the group, such as "View". */
  heading?: string;
  /** `MenuItem`s. */
  children: ReactNode;
  /**
   * Whether its items can be checked: `multiple` for checkboxes, `single` for
   * a choice of one (radios). Give each item an `id`. Defaults to `none`.
   */
  selectionMode?: "none" | "single" | "multiple";
  /** The ids of the checked items, for a controlled section. */
  selectedKeys?: Iterable<string>;
  /** The ids of the items checked at first, for an uncontrolled one. */
  defaultSelectedKeys?: Iterable<string>;
  /** Called with the ids of the checked items when one is checked or unchecked. */
  onSelectionChange?: (keys: Set<string>) => void;
  /** Names the group for screen readers when it has no `heading`. */
  "aria-label"?: string;
}

/**
 * A titled group of items. With a `selectionMode` its items can be checked, as
 * a set of options that stay on or off, or as a choice of one.
 */
export function MenuSection({
  heading,
  children,
  selectionMode,
  selectedKeys,
  defaultSelectedKeys,
  onSelectionChange,
  "aria-label": ariaLabel,
}: MenuSectionProps) {
  return (
    <AriaMenuSection
      aria-label={heading ? undefined : ariaLabel}
      selectionMode={selectionMode}
      selectedKeys={selectedKeys}
      defaultSelectedKeys={defaultSelectedKeys}
      onSelectionChange={
        onSelectionChange
          ? (keys) =>
              // "all" only comes from a select-all key, which a menu does not have.
              onSelectionChange(
                keys === "all" ? new Set() : (keys as Set<string>),
              )
          : undefined
      }
      className={styles.section()}
    >
      {heading ? <Header className={styles.heading()}>{heading}</Header> : null}
      {children}
    </AriaMenuSection>
  );
}

export interface MenuSubmenuProps {
  /** What the item that opens the submenu says. */
  label: ReactNode;
  /** An icon before the label. */
  icon?: ReactNode;
  /** The text a typed letter is matched to, when the label is not text. */
  textValue?: string;
  /** The items of the submenu. */
  children: ReactNode;
  isDisabled?: boolean;
  /** A stable name for it. */
  id?: string;
  /** Names the submenu for screen readers. Defaults to the label. */
  "aria-label"?: string;
}

/**
 * An item that opens another menu to its side, on hover or with the right arrow
 * key. Its items are `MenuItem`s, and it can hold sections and other
 * submenus.
 */
export function MenuSubmenu({
  label,
  icon,
  textValue,
  children,
  isDisabled,
  id,
  "aria-label": ariaLabel,
}: MenuSubmenuProps) {
  const generatedId = useId();
  const name = textValue ?? (typeof label === "string" ? label : undefined);

  return (
    <SubmenuTrigger>
      <MenuItem
        id={id ?? generatedId}
        icon={icon}
        textValue={name}
        isDisabled={isDisabled}
      >
        {label}
      </MenuItem>
      <Popover offset={-4} className={styles.popover()}>
        <AriaMenu
          aria-label={ariaLabel ?? name ?? "Submenu"}
          onContextMenu={(event) => event.preventDefault()}
          className={styles.menu()}
        >
          {children}
        </AriaMenu>
      </Popover>
    </SubmenuTrigger>
  );
}

/** A line between two groups. */
export function MenuSeparator() {
  return <Separator className={styles.separator()} />;
}

3. Use it

import {
  Menu,
  MenuContent,
  MenuItem,
  MenuSection,
  MenuSeparator,
  MenuSubmenu,
  MenuTrigger,
} from "@/components/ui/menu/menu";

Anatomy

A button, and a panel with the items.

<Menu>
  <MenuTrigger>Options</MenuTrigger>
  <MenuContent aria-label="Options">
    <MenuSection heading="File">
      <MenuItem icon={<CopyIcon />} shortcut="⌘ D" description="Make a copy">Duplicate</MenuItem>
      <MenuSubmenu label="Move to">
        <MenuItem>Inbox</MenuItem>
      </MenuSubmenu>
    </MenuSection>
    <MenuSeparator />
    <MenuItem variant="danger">Delete</MenuItem>
  </MenuContent>
</Menu>
PartRendered asNotes
Menu-Holds the open state. It has no look of its own.
MenuTriggerbuttonThe button that opens it: a Button, with a small arrow.
MenuContentmenuThe panel next to the button, with the items. It turns to the other side when there is no room.
MenuItemmenuitemOne action: a name, and if you like an icon, a line of description and the keys.
MenuSectiongroupA titled group of items. It can make its items checkable.
MenuSubmenumenuitemAn item that opens another menu to its side.
MenuSeparatorseparatorA line between two groups.

Keyboard

KeyWhat it does
Enter, Space, ↓On the button, opens the menu with the first item focused. ↑ opens it with the last.
↓ ↑Moves to the next or the previous item.
→On an item with a submenu, opens it.
←In a submenu, closes it.
A letterJumps to the item that starts with what is typed.
Enter or SpaceRuns the item, or checks it.
Home, EndGoes to the first or the last item.
EscapeCloses the menu, and the focus goes back to the button.

Examples

Usage

Items run onAction when they are chosen, and the menu closes.

Last action: nothing yet

An icon button

For the actions of a row or a card: an icon-only trigger, with an aria-label, and the panel at its end.

Last action: nothing yet

Descriptions

A second line says more about an item.

Sections

A heading and a line between groups make a long menu easier to read.

Checkable items

selectionMode makes the items of a section checkable: multiple for options that stay on or off, single for a choice of one. Give each item an id, which is what selectedKeys holds. A checkbox leaves the menu open, and a choice of one closes it.

Show: toolbar, status · Density: comfortable

Controlled

isOpen and onOpenChange, to open it from somewhere else or to know that it is open.

It is closed

Placement

Where the panel opens, relative to the button: the side (bottom, top, left, right, or start and end, which follow the reading direction) and where along it (start, end, left, right, top, bottom). Naming only the side centers it. It turns to the other side when there is no room.

Width

matchTriggerWidth makes the panel at least as wide as the button.

Press and hold

trigger longPress opens the menu with a press and hold (or Alt+↓) and leaves the press itself to the button, for a button that does something when it is pressed.

Disabled

Component API

Each part takes the props of its table.

Menu

PropTypeDefault
isOpenboolean-
defaultOpenbooleanfalse
onOpenChange(isOpen: boolean) => void-
trigger"press" | "longPress""press"

MenuTrigger

PropTypeDefault
childrenReactNode-
variant"outline" | "secondary" | "ghost" | …"outline"
sizethe sizes of Button"md"
isIconbooleanfalse
showChevronbooleantrue, unless isIcon
…restthe props of Button-

MenuContent

PropTypeDefault
aria-labelstring"Menu"
placementPlacement (22 values, see Placement)"bottom start"
offsetnumber6
crossOffsetnumber0
shouldFlipbooleantrue
matchTriggerWidthbooleanfalse
disabledKeysIterable<Key>-
onAction(key: Key) => void-
autoFocusboolean | "first" | "last"true
classNamestring-

MenuItem

PropTypeDefault
childrenReactNode-
onAction() => void-
iconReactNode-
descriptionReactNode-
shortcutstring-
variant"default" | "danger""default"
hrefstring-
textValuestringthe name
closeOnActionbooleantrue
isDisabledbooleanfalse
idstringmade up

MenuSection

PropTypeDefault
headingstring-
selectionMode"none" | "single" | "multiple""none"
selectedKeysIterable<string>-
defaultSelectedKeysIterable<string>-
onSelectionChange(keys: Set<string>) => void-
aria-labelstring-

MenuSubmenu

PropTypeDefault
labelReactNode-
iconReactNode-
textValuestringthe label
isDisabledbooleanfalse
idstringmade up
aria-labelstringthe label