# How to Build a Command Palette in React (Cmd+K)

URL: https://beui.dev/blog/react-command-palette
Published: 2026-11-30

Your app has dozens of actions spread across menus. Power users want one shortcut that gets them anywhere. A react command palette fixes that.

Press Cmd+K, type two letters, press Enter. It looks like an input and a list. The hard part is everything around it: keyboard handling, focus, screen readers and an animation that never feels slow.

This guide builds one from scratch in under 200 lines, then shows the finished version in [beUI](https://beui.dev) you can install with one command.

## What does a React command palette need?

Before writing code, list the behavior. A palette people trust does all of this:

- Opens with Cmd+K on macOS and Ctrl+K elsewhere, from anywhere on the page.
- Renders as a modal dialog with the search field focused.
- Filters the commands as you type.
- Moves an active row with the arrow keys, while focus stays in the input.
- Runs the active command on Enter and closes on Escape or a backdrop click.
- Returns focus to whatever was focused before it opened.
- Tells screen readers what is going on, using a combobox that controls a listbox.
- Animates in and out fast, and drops the movement for people who ask for reduced motion.

## How do you build a command palette in React?

Here is the whole component. It uses React 19, Tailwind CSS 4 and Framer Motion (imported from `motion/react`).

```tsx title="command-palette.tsx"
"use client";

import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useEffect, useId, useRef, useState } from "react";

export type Command = {
  id: string;
  label: string;
  run: () => void;
};

const EASE_OUT = [0.16, 1, 0.3, 1] as const;

export function CommandPalette({ commands }: { commands: Command[] }) {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState("");
  const [activeId, setActiveId] = useState<string | null>(null);
  const returnFocus = useRef<HTMLElement | null>(null);
  const listId = useId();
  const reduce = useReducedMotion();

  const openPalette = () => {
    returnFocus.current = document.activeElement as HTMLElement | null;
    setQuery("");
    setActiveId(null);
    setOpen(true);
  };

  const closePalette = () => {
    setOpen(false);
    returnFocus.current?.focus();
  };

  // Cmd+K on macOS, Ctrl+K everywhere else. Toggles from anywhere.
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
        e.preventDefault();
        if (open) closePalette();
        else openPalette();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  const q = query.trim().toLowerCase();
  const results = q
    ? commands.filter((c) => c.label.toLowerCase().includes(q))
    : commands;

  // Resolve the active row during render: the stored id if it is still
  // in the results, otherwise the first row.
  const found = results.findIndex((c) => c.id === activeId);
  const active = results[found === -1 ? 0 : found];

  const move = (delta: number) => {
    setActiveId((prev) => {
      if (results.length === 0) return null;
      const i = results.findIndex((c) => c.id === prev);
      const from = i === -1 ? 0 : i;
      return results[(from + delta + results.length) % results.length].id;
    });
  };

  const runCommand = (command: Command) => {
    closePalette();
    command.run();
  };

  useEffect(() => {
    if (!active) return;
    document
      .getElementById(`${listId}-${active.id}`)
      ?.scrollIntoView({ block: "nearest" });
  }, [active, listId]);

  const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "ArrowDown") {
      e.preventDefault();
      move(1);
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      move(-1);
    } else if (e.key === "Enter") {
      if (e.nativeEvent.isComposing) return;
      e.preventDefault();
      if (active) runCommand(active);
    } else if (e.key === "Escape") {
      e.preventDefault();
      closePalette();
    } else if (e.key === "Tab") {
      // The input is the only focusable element, so keep focus inside.
      e.preventDefault();
    }
  };

  return (
    <AnimatePresence>
      {open && (
        <motion.div
          key="backdrop"
          aria-hidden
          className="fixed inset-0 z-50 bg-black/40"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0, transition: { duration: 0.12 } }}
          transition={{ duration: 0.18, ease: EASE_OUT }}
          onClick={closePalette}
        />
      )}
      {open && (
        <motion.div
          key="panel"
          role="dialog"
          aria-modal="true"
          aria-label="Command palette"
          className="fixed inset-x-4 top-[15vh] z-50 mx-auto max-w-lg overflow-hidden rounded-2xl border bg-white shadow-xl dark:bg-neutral-900"
          initial={{ opacity: 0, y: reduce ? 0 : -8, scale: reduce ? 1 : 0.96 }}
          animate={{ opacity: 1, y: 0, scale: 1 }}
          exit={{
            opacity: 0,
            y: reduce ? 0 : -8,
            scale: reduce ? 1 : 0.96,
            transition: { duration: 0.12, ease: EASE_OUT },
          }}
          transition={{ duration: 0.18, ease: EASE_OUT }}
        >
          <input
            autoFocus
            value={query}
            onChange={(e) => {
              setQuery(e.target.value);
              setActiveId(null);
            }}
            onKeyDown={onKeyDown}
            placeholder="Type a command…"
            role="combobox"
            aria-expanded="true"
            aria-controls={listId}
            aria-autocomplete="list"
            aria-activedescendant={active ? `${listId}-${active.id}` : undefined}
            className="h-12 w-full border-b bg-transparent px-4 text-sm outline-none"
          />
          <ul
            id={listId}
            role="listbox"
            aria-label="Commands"
            className="max-h-72 overflow-y-auto p-2"
          >
            {results.map((command) => (
              <li
                key={command.id}
                id={`${listId}-${command.id}`}
                role="option"
                aria-selected={command.id === active?.id}
                onMouseMove={() => setActiveId(command.id)}
                onMouseDown={(e) => e.preventDefault()}
                onClick={() => runCommand(command)}
                className="cursor-pointer rounded-lg px-3 py-2 text-sm aria-selected:bg-neutral-100 dark:aria-selected:bg-neutral-800"
              >
                {command.label}
              </li>
            ))}
          </ul>
          {results.length === 0 && (
            <p className="p-6 text-center text-sm text-neutral-500">
              No results
            </p>
          )}
        </motion.div>
      )}
    </AnimatePresence>
  );
}
```

And using it:

```tsx title="app.tsx"
import { CommandPalette, type Command } from "./command-palette";

const commands: Command[] = [
  { id: "home", label: "Go to home", run: () => window.location.assign("/") },
  { id: "settings", label: "Open settings", run: () => window.location.assign("/settings") },
  {
    id: "theme",
    label: "Toggle dark mode",
    run: () => document.documentElement.classList.toggle("dark"),
  },
];

export function App() {
  return <CommandPalette commands={commands} />;
}
```

## Why resolve the active row during render?

The tempting version stores an index and resets it in a `useEffect` when the query changes. That leaves a gap: for one commit the index points at a row that moved or no longer exists. Press Enter in that window and you run the wrong command.

This palette stores the active command's **id**, not its position, and works out the row in render. If the id is gone from the results, the first row is active. Typing clears the id, so the first match is always the default. The arrow keys use a functional update, so two quick presses move two rows.

## How do you make a command palette accessible?

Focus never leaves the input. The arrow keys change `aria-activedescendant`, which tells screen readers which `role="option"` is active without moving focus. The input is a `role="combobox"` that points at the `role="listbox"` through `aria-controls`, and the whole panel is a `role="dialog"` with `aria-modal`.

Three details are easy to miss:

- **Focus return.** `openPalette` saves `document.activeElement`, and `closePalette` focuses it again. Without this, keyboard users land at the top of the page after every command.
- **Mouse without stealing focus.** `onMouseDown` calls `preventDefault`, so clicking a row never blurs the input.
- **IME input.** The `isComposing` check stops Enter from running a command while someone is confirming a Japanese or Chinese character.

## How do you animate a command palette with Framer Motion?

`AnimatePresence` keeps the backdrop and panel mounted until their `exit` animations finish. The panel fades, drops 8px and scales from 0.96 in 180ms, and leaves faster in 120ms. A palette you open many times a day has to feel instant, so keep it short.

`useReducedMotion()` returns true when the user turned on reduced motion. The panel then skips the `y` and `scale` change and only fades. The CSS media query can't stop JS-driven animations, so the hook is what does the work. The [reduced motion guide](https://beui.dev/guides/reduced-motion-framer-motion) covers the pattern in more depth.

What this version leaves out: page scroll lock while open, grouped results, ranked fuzzy search and a portal so a transformed parent can't trap the fixed layer. Those are the next things you will want.

## Using the beUI command palette

The [beUI command palette](https://beui.dev/components/blocks/command-palette) is a finished version of the same idea. It adds grouped results, ranked search over labels, groups and keywords, icons, shortcut hints, a spring-animated active row, scroll lock and a portal to `<body>`. It uses the same combobox and listbox roles and respects reduced motion.

Install it with the shadcn CLI:

```bash
npx shadcn@latest add @beui/command-palette
```

Then pass it a list of items. Each item takes an `id`, a `label`, an `onSelect` callback and optional `group`, `icon`, `hint` and `keywords`:

```tsx title="app-command-palette.tsx"
"use client";

import { FileText, Home, Plus, Settings, User } from "lucide-react";
import { useState } from "react";
import { CommandPalette } from "@/components/motion/command-palette";

export function AppCommandPalette() {
  const [open, setOpen] = useState(false);

  return (
    <>
      <button type="button" onClick={() => setOpen(true)}>
        Open command palette
      </button>
      <CommandPalette
        open={open}
        onOpenChange={setOpen}
        items={[
          { id: "home", label: "Go to Home", group: "Navigation", icon: Home, hint: "G H", onSelect: () => {} },
          { id: "profile", label: "Open profile", group: "Navigation", icon: User, hint: "G P", onSelect: () => {} },
          { id: "settings", label: "Settings", group: "Navigation", icon: Settings, onSelect: () => {} },
          { id: "new-doc", label: "Create document", group: "Actions", icon: FileText, hint: "⌘ N", onSelect: () => {} },
          { id: "new-project", label: "New project", group: "Actions", icon: Plus, hint: "⌘ ⇧ N", onSelect: () => {} },
        ]}
      />
    </>
  );
}
```

Cmd+K or Ctrl+K opens it by default. Pass `shortcut="j"` to use a different key. Leave out `open` and `onOpenChange` and it manages its own state. Every visible string, including the placeholder and the screen reader labels, can be replaced through the `labels` prop for translations.

If you want search that grows out of a field instead of a centered dialog, look at [morphing search](https://beui.dev/components/blocks/morphing-search).

## FAQ

### What is the best way to add a Cmd+K menu in React?

Listen for `keydown` on `window`, check `metaKey || ctrlKey` with the `k` key, and call `preventDefault` so the browser shortcut does not fire. Render the palette as a modal dialog with the input focused.

### Which ARIA roles should a command palette use?

A `dialog` with `aria-modal` around a `combobox` input that controls a `listbox` of `option` elements. Point `aria-activedescendant` at the active option so focus can stay in the input.

### Should a command palette use fuzzy search?

For a short list, a simple `includes` match is fine. Once you have many commands, ranked matching over labels and keywords helps, which is what the beUI palette does.

## Takeaway

A command palette is small, but every detail is visible to keyboard users: the active row, where focus goes and how fast it opens. Get those right first, then add the motion.

Grab the finished one from [beUI](https://beui.dev):

```bash
npx shadcn@latest add @beui/command-palette
```
