Menu

Components

Command Menu

A search box over a list of things to do, opened with a key from anywhere: type, move with the arrows, press Enter.

Introduction

Command Menu, or command palette, is a search box over a list of what the user can do: go to a page, start something new, change a setting. It opens with a key from anywhere, filters as they type, and runs a command with Enter, so the whole app is a few keys away.

  • Built on react-aria's Autocomplete, Menu and Modal. The cursor stays in the search box while the arrow keys move through the list, and focus goes back to where it was when the menu closes.
  • Commands are found by their name, their description and keywords: "preferences" can find Settings. A group whose commands all fail to match is hidden, and when nothing matches it says so.
  • Groups with titles, separators, icons, a line of description, the keys of a command, disabled and dangerous commands, and links.
  • A shortcut such as k opens and closes it with Command (or Ctrl) from anywhere, and the trigger shows the keys written for the platform, ⌘K on a Mac and Ctrl K elsewhere.
  • It opens over a dimmed page with a short entrance, and not for people who prefer reduced motion.

The keys shown on a command with shortcut are only shown: the command does not listen for them. Wire them up with your own key handling. The examples here use other keys than ⌘K, which opens the search of this site. It is a Client Component.

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

Copy these files into your project and keep the paths, or adjust the imports. It uses Button and the search icon, and the dialog animations in globals.css.

1. Add the styles

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

// Styles for CommandMenu. `dialog-overlay` and `dialog-modal` give the backdrop and
// the panel their entrance and exit animations (see globals.css, they are the
// same as a Dialog's).
export const commandMenuStyles = tv({
  slots: {
    overlay:
      "dialog-overlay fixed inset-0 z-50 flex items-start justify-center bg-black/40 p-4 pt-[12vh] backdrop-blur-sm",
    modal:
      "dialog-modal flex max-h-[min(30rem,calc(100dvh-2rem))] w-full flex-col overflow-hidden rounded-2xl border bg-card text-card-fg shadow-2xl outline-none",
    dialog: "flex min-h-0 flex-1 flex-col outline-none",
    search: "flex shrink-0 items-center gap-3 border-b px-4",
    searchIcon: "size-4 shrink-0 text-muted-fg",
    input:
      "h-12 min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-fg [&::-webkit-search-cancel-button]:hidden",
    list: "min-h-0 flex-1 overflow-y-auto p-2 outline-none",
    group: "flex flex-col [&:not(:first-child)]:mt-1",
    heading: "px-3 pt-2 pb-1 text-xs font-medium text-muted-fg",
    item: [
      "group/item flex cursor-default items-center gap-3 rounded-lg px-3 py-2 text-sm outline-none select-none",
      "data-focused:bg-muted data-pressed:bg-muted/70",
      "data-disabled:cursor-not-allowed data-disabled:opacity-50",
      "data-[variant=danger]:text-danger",
    ],
    icon: "flex size-4 shrink-0 items-center justify-center text-muted-fg [&_svg]:size-4",
    text: "flex min-w-0 flex-1 flex-col",
    label: "truncate font-medium",
    description: "truncate text-xs text-muted-fg",
    shortcut:
      "ml-auto flex shrink-0 items-center gap-1 font-sans text-xs text-muted-fg",
    kbd: "inline-flex h-5 min-w-5 items-center justify-center rounded border bg-muted px-1 font-sans text-[11px] leading-5 text-muted-fg",
    separator: "-mx-2 my-1 h-px border-0 bg-border",
    empty: "px-4 py-10 text-center text-sm text-muted-fg",
    footer:
      "flex shrink-0 items-center gap-4 border-t px-4 py-2 text-xs text-muted-fg",
    hint: "inline-flex items-center gap-1.5",
    trigger: "min-w-40 justify-start gap-2 font-normal text-muted-fg",
  },
  variants: {
    size: {
      md: { modal: "max-w-lg" },
      lg: { modal: "max-w-2xl" },
    },
  },
  defaultVariants: { size: "md" },
});

2. Add the Command Menu file

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

import {
  createContext,
  type ReactNode,
  useContext,
  useEffect,
  useId,
  useRef,
  useState,
} from "react";
import {
  Autocomplete,
  Dialog,
  DialogTrigger,
  Header,
  Input,
  Menu,
  MenuItem,
  MenuSection,
  Modal,
  ModalOverlay,
  OverlayTriggerStateContext,
  SearchField,
  Separator,
  Text,
  useFilter,
} from "react-aria-components";
import { ChevronDownIcon, ChevronUpIcon, SearchIcon } from "@/components/icons";
import { Button } from "@/components/ui/button/button";
import { cn } from "@/lib/cn";
import { commandMenuStyles } from "@/types/command-menu-styles";
import { useIsMac } from "@/types/use-is-mac";

const ShortcutContext = createContext<string | undefined>(undefined);

export interface CommandMenuProps {
  /** A `CommandMenuTrigger` or any button that opens it, and the `CommandMenuContent`. */
  children: ReactNode;
  /** Whether it is open, for a controlled menu. */
  isOpen?: boolean;
  /** Whether it starts open, for an uncontrolled one. Defaults to `false`. */
  defaultOpen?: boolean;
  /** Called when it opens or closes. */
  onOpenChange?: (isOpen: boolean) => void;
  /**
   * A key that opens and closes the menu together with Command (or Ctrl), from
   * anywhere on the page: `"k"` for the usual Command+K. Off unless set.
   */
  shortcut?: string;
}

/**
 * A command menu, also called a command palette: a search box over a list of
 * things the user can do, opened with a key from anywhere, filtered as they
 * type, and chosen with the arrow keys and Enter. Use it for the actions and
 * pages of an app, so that they are a few keys away instead of in a menu, or a
 * settings page, or a place the user has to remember.
 *
 * Put a `CommandMenuTrigger` (or your own button) and a `CommandMenuContent` in
 * it. The content has the search box, and groups of `CommandMenuItem`s. Built on
 * react-aria's Autocomplete, Menu and Modal, so the keyboard, the screen reader
 * announcements and focus (into the search box, and back to where it was when
 * the menu closes) come from there.
 *
 * @example
 * <CommandMenu shortcut="k">
 *   <CommandMenuTrigger />
 *   <CommandMenuContent>
 *     <CommandMenuGroup heading="Go to">
 *       <CommandMenuItem onAction={() => router.push("/")}>Home</CommandMenuItem>
 *     </CommandMenuGroup>
 *   </CommandMenuContent>
 * </CommandMenu>
 */
export function CommandMenu({
  children,
  isOpen,
  defaultOpen = false,
  onOpenChange,
  shortcut,
}: CommandMenuProps) {
  const [inner, setInner] = useState(defaultOpen);
  const open = isOpen ?? inner;
  const openRef = useRef(open);
  openRef.current = open;

  function setOpen(next: boolean) {
    if (isOpen === undefined) setInner(next);
    onOpenChange?.(next);
  }
  // The latest, so the key listener is not put on again at every render.
  const setOpenRef = useRef(setOpen);
  setOpenRef.current = setOpen;

  useEffect(() => {
    if (!shortcut) return;
    const key = shortcut.toLowerCase();
    function onKeyDown(event: KeyboardEvent) {
      if (
        (event.metaKey || event.ctrlKey) &&
        !event.altKey &&
        !event.shiftKey &&
        event.key.toLowerCase() === key
      ) {
        event.preventDefault();
        setOpenRef.current(!openRef.current);
      }
    }
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [shortcut]);

  return (
    <ShortcutContext.Provider value={shortcut}>
      <DialogTrigger isOpen={open} onOpenChange={setOpen}>
        {children}
      </DialogTrigger>
    </ShortcutContext.Provider>
  );
}

// "⌘K", "Ctrl K" and "⌘ ⇧ P" become one key each.
function keysOf(shortcut: string) {
  return shortcut
    .split(/[\s+]+/)
    .filter(Boolean)
    .flatMap((token) => (/^[⌘⇧⌥⌃]+.$/u.test(token) ? [...token] : [token]));
}

function Keys({
  shortcut,
  className,
  kbd,
}: {
  shortcut: string;
  className: string;
  kbd: string;
}) {
  return (
    // 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.
    <span className={className}>
      {keysOf(shortcut).map((key, i) => (
        // biome-ignore lint/suspicious/noArrayIndexKey: the keys are the positions
        <kbd key={i} className={kbd}>
          {key}
        </kbd>
      ))}
    </span>
  );
}

const styles = commandMenuStyles();

export interface CommandMenuTriggerProps {
  /** What it says. Defaults to "Search…". */
  children?: ReactNode;
  variant?: "outline" | "secondary" | "ghost";
  size?: "sm" | "md" | "lg";
  /** Only the icon, for a small place. Give it an `aria-label`. */
  isIcon?: boolean;
  "aria-label"?: string;
  className?: string;
}

/**
 * The button that opens a `CommandMenu`. It shows a search icon, what it says,
 * and, if the menu has a `shortcut`, the keys, written for the platform: ⌘K on a
 * Mac and Ctrl K elsewhere.
 */
export function CommandMenuTrigger({
  children = "Search…",
  variant = "outline",
  size,
  isIcon,
  "aria-label": ariaLabel,
  className,
}: CommandMenuTriggerProps) {
  const shortcut = useContext(ShortcutContext);
  const isMac = useIsMac();

  return (
    <Button
      variant={variant}
      size={size}
      isIcon={isIcon}
      aria-label={ariaLabel}
      className={cn(!isIcon && styles.trigger(), className)}
    >
      <SearchIcon />
      {isIcon ? null : (
        <>
          <span className="flex-1 text-left">{children}</span>
          {shortcut ? (
            <Keys
              shortcut={`${isMac ? "⌘" : "Ctrl"} ${shortcut.toUpperCase()}`}
              className={styles.shortcut()}
              kbd={styles.kbd()}
            />
          ) : null}
        </>
      )}
    </Button>
  );
}

export interface CommandMenuContentProps {
  /** `CommandMenuGroup`s and `CommandMenuItem`s, and `CommandMenuSeparator`s. */
  children: ReactNode;
  /** What the search box says when it is empty. Defaults to "Type a command or search…". */
  placeholder?: string;
  /** What is shown when nothing matches. Defaults to "No results found." */
  emptyText?: ReactNode;
  /** How wide the panel is. Defaults to `md`. */
  size?: "md" | "lg";
  /** The line of hints under the list: the keys to move, choose and close. Defaults to `true`. */
  showFooter?: boolean;
  /** Decides if an item matches what was typed: `(text, input) => boolean`. Defaults to "contains", ignoring case and accents. */
  filter?: (textValue: string, inputValue: string) => boolean;
  /** Closes when the user clicks outside. Defaults to `true`. */
  isDismissable?: boolean;
  /** Names the menu for screen readers. Defaults to "Command menu". */
  "aria-label"?: string;
  className?: string;
}

/**
 * The panel of a `CommandMenu`: a search box, and under it the list of commands,
 * filtered as the user types. The arrow keys move through the list while the
 * cursor stays in the search box, Enter runs the command, and Escape closes it.
 */
export function CommandMenuContent({
  children,
  placeholder = "Type a command or search…",
  emptyText = "No results found.",
  size,
  showFooter = true,
  filter,
  isDismissable = true,
  "aria-label": ariaLabel = "Command menu",
  className,
}: CommandMenuContentProps) {
  const { contains } = useFilter({ sensitivity: "base" });
  const classes = commandMenuStyles({ size });

  return (
    <ModalOverlay isDismissable={isDismissable} className={classes.overlay()}>
      <Modal className={cn(classes.modal(), className)}>
        <Dialog aria-label={ariaLabel} className={classes.dialog()}>
          <Autocomplete filter={filter ?? contains}>
            <SearchField
              autoFocus
              aria-label={placeholder}
              className={classes.search()}
            >
              <SearchIcon className={classes.searchIcon()} />
              <Input placeholder={placeholder} className={classes.input()} />
              {/* Decorative, the way the footer's own hints are: Escape
                  already closes the menu from anywhere, this just says so. */}
              <kbd aria-hidden="true" tabIndex={-1} className={classes.kbd()}>
                Esc
              </kbd>
            </SearchField>
            <Menu
              aria-label={ariaLabel}
              renderEmptyState={() => (
                <div className={classes.empty()}>{emptyText}</div>
              )}
              className={classes.list()}
            >
              {children}
            </Menu>
          </Autocomplete>
          {showFooter ? (
            <div className={classes.footer()}>
              <span className={classes.hint()}>
                <kbd className={classes.kbd()}>
                  <ChevronUpIcon className="size-3" />
                </kbd>
                <kbd className={classes.kbd()}>
                  <ChevronDownIcon className="size-3" />
                </kbd>{" "}
                to move
              </span>
              <span className={classes.hint()}>
                <kbd className={classes.kbd()}>↵</kbd> to choose
              </span>
              <span className={cn(classes.hint(), "ml-auto")}>
                <kbd className={classes.kbd()}>esc</kbd> to close
              </span>
            </div>
          ) : null}
        </Dialog>
      </Modal>
    </ModalOverlay>
  );
}

export interface CommandMenuGroupProps {
  /** The title of the group, such as "Suggestions". It is left out while none of its items match. */
  heading?: string;
  children: ReactNode;
  /** Names the group for screen readers when it has no `heading`. */
  "aria-label"?: string;
}

/** A titled group of commands. */
export function CommandMenuGroup({
  heading,
  children,
  "aria-label": ariaLabel,
}: CommandMenuGroupProps) {
  return (
    <MenuSection
      aria-label={heading ? undefined : ariaLabel}
      className={styles.group()}
    >
      {heading ? <Header className={styles.heading()}>{heading}</Header> : null}
      {children}
    </MenuSection>
  );
}

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

export interface CommandMenuItemProps {
  /** What the command is called. */
  children: ReactNode;
  /** Runs when the command is chosen, by Enter or by a press. */
  onAction?: () => void;
  /** An icon before the name. */
  icon?: ReactNode;
  /** A line under the name that says more. It is searched too. */
  description?: string;
  /** The keys of the command, shown at the end of the row, such as `"⌘ N"`. They are only shown: the command does not listen for them. */
  shortcut?: string;
  /** Other words that find it, such as "preferences" for Settings. */
  keywords?: string[];
  /** The text it is searched and announced by, when the name is not text. Defaults to the name. */
  textValue?: string;
  /** Red, for a command that destroys something. */
  variant?: "default" | "danger";
  /** Close the menu after the command runs. Defaults to `true`. */
  closeOnAction?: boolean;
  /** Makes it a link to this address instead of running a function. */
  href?: string;
  isDisabled?: boolean;
  /** A stable name for it. Made up for you unless set. */
  id?: string;
}

/**
 * One command in the list: a name, and if you like an icon, a line of
 * description and the keys. It is found by its name, its description and its
 * `keywords`, and closes the menu after it runs.
 */
export function CommandMenuItem({
  children,
  onAction,
  icon,
  description,
  shortcut,
  keywords,
  textValue,
  variant = "default",
  closeOnAction = true,
  href,
  isDisabled,
  id,
}: CommandMenuItemProps) {
  const state = useContext(OverlayTriggerStateContext);
  // An item keeps one id for as long as it is there, even when its name changes.
  const generatedId = useId();
  const name = textValue ?? (typeof children === "string" ? children : "");
  // Everything the search looks at: the name, then what else finds it.
  const searchText = [name, description, ...(keywords ?? [])]
    .filter(Boolean)
    .join(" ");

  return (
    <MenuItem
      id={id ?? generatedId}
      textValue={searchText}
      href={href}
      isDisabled={isDisabled}
      // react-aria closes a menu when an item is chosen: say when it should not.
      shouldCloseOnSelect={closeOnAction}
      data-variant={variant}
      onAction={() => {
        onAction?.();
        if (closeOnAction) state?.close();
      }}
      className={styles.item()}
    >
      {icon ? (
        <span aria-hidden="true" className={styles.icon()}>
          {icon}
        </span>
      ) : null}
      <div className={styles.text()}>
        <Text slot="label" className={styles.label()}>
          {children}
        </Text>
        {description ? (
          <Text slot="description" className={styles.description()}>
            {description}
          </Text>
        ) : null}
      </div>
      {shortcut ? (
        <Keys
          shortcut={shortcut}
          className={styles.shortcut()}
          kbd={styles.kbd()}
        />
      ) : null}
    </MenuItem>
  );
}

3. Use it

import {
  CommandMenu,
  CommandMenuContent,
  CommandMenuGroup,
  CommandMenuItem,
  CommandMenuSeparator,
  CommandMenuTrigger,
} from "@/components/ui/command-menu/command-menu";

Anatomy

A trigger, and a panel with a search box, groups of commands and a line of hints.

<CommandMenu shortcut="k">
  <CommandMenuTrigger />
  <CommandMenuContent placeholder="Type a command or search…">
    <CommandMenuGroup heading="Suggestions">
      <CommandMenuItem icon={<HomeIcon />} shortcut="⌘ H" onAction={goHome}>
        Go to Home
      </CommandMenuItem>
    </CommandMenuGroup>
    <CommandMenuSeparator />
    <CommandMenuGroup heading="Settings">
      <CommandMenuItem keywords={["preferences"]}>Settings</CommandMenuItem>
    </CommandMenuGroup>
  </CommandMenuContent>
</CommandMenu>
PartRendered asNotes
CommandMenu-Holds the open state and, if you give a shortcut, listens for the key. It has no look of its own.
CommandMenuTriggerbuttonThe button that opens it: a search icon, a label, and the keys of the shortcut.
CommandMenuContentdialogThe panel over a dimmed page: the search box, the list, and a line of hints under it.
CommandMenuGroupmenu sectionA titled group of commands. Its title goes when none of its commands match.
CommandMenuItemmenu itemOne command: a name, and if you like an icon, a description and the keys.
CommandMenuSeparatorseparatorA line between two groups.

Keyboard

It is made to be used without the mouse.

KeyWhat it does
Command K (or your shortcut)Open the menu from anywhere, and close it while it is open.
TypeFilter the commands. The cursor stays in the search box.
Arrow Down, Arrow UpMove through the commands, without leaving the search box. The list wraps at its ends.
EnterRun the command that is marked, and close the menu.
EscapeClose the menu, and give focus back to where it was.

Examples

Usage

Press the button, or Command (Ctrl) J, and type to filter.

Press the button, or Command (Ctrl) J, and pick a command.

Items

A command has a name, and can have an icon, a description, keys, and other words that find it. It can be disabled, dangerous, or stay open when it runs.

Mode: light (the menu stays open when it is changed).

Controlled

Own the open state with isOpen and onOpenChange, to open it from another button or to know when it is open.

Closed

Texts and hints

Change what the search box says when it is empty, what is shown when nothing matches, and leave out the line of hints under the list.

Sizes

Triggers

A button with a label and the keys, a quiet one, or only an icon for a small place.

Filtering

By default an item is found when its name, description or keywords contain what was typed, ignoring case and accents. filter replaces the rule.

<CommandMenuContent
  // Only the items that start with what was typed
  filter={(text, input) => text.toLowerCase().startsWith(input.toLowerCase())}
>
  ...
</CommandMenuContent>

Component API

Command Menu is made of the parts below.

CommandMenu

PropTypeDefault
childrenReactNode-
shortcutstring- (off)
isOpenboolean-
defaultOpenbooleanfalse
onOpenChange(isOpen: boolean) => void-

CommandMenuTrigger

PropTypeDefault
childrenReactNode"Search…"
variant"outline" | "secondary" | "ghost""outline"
size"sm" | "md" | "lg"-
isIconbooleanfalse
aria-labelstring-
classNamestring-

CommandMenuContent

PropTypeDefault
childrenReactNode-
placeholderstring"Type a command or search…"
emptyTextReactNode"No results found."
size"md" | "lg""md"
showFooterbooleantrue
filter(text: string, input: string) => booleancontains, ignoring case and accents
isDismissablebooleantrue
aria-labelstring"Command menu"
classNamestring-

CommandMenuGroup

PropTypeDefault
headingstring-
aria-labelstring- (when there is no heading)
childrenReactNode-

CommandMenuItem

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