All questions

Command Palette

Premium

Command Palette

Build a ⌘K-style command palette in React — the overlay you summon with a keyboard shortcut to jump straight to an action. It is the Spotlight / VS Code pattern: an input, a filtered list, arrow-key navigation, and Enter to run. The interesting part is not the list; it is the interplay of an autofocused input, keyboard-driven selection, and open/close from three different triggers.

What you'll build

The starter renders only the trigger button and an empty status line (the palette is closed). Make it work:

  1. Open it. Clicking the trigger, or pressing ⌘K / Ctrl+K anywhere on the page, opens the overlay. On open, the search input is autofocused so the user can type immediately.
  2. Filter as you type. Typing narrows the six commands to those whose label contains the query (case-insensitive substring).
  3. Navigate with the keyboard. ArrowDown / ArrowUp move an active highlight through the filtered list and wrap at the ends. Enter runs the active command.
  4. Run a command. Clicking a row or pressing Enter runs it: the palette closes and the status line shows Ran: <label>.
  5. Close it. Escape, or a click on the backdrop, closes the palette without running anything.

Examples

  • Press ⌘K: the overlay appears and the caret is already blinking in the input. Type se and the list shrinks to Open Settings and Search Docs.
  • With se typed, ArrowDown moves the highlight to Search Docs; ArrowDown again wraps back to Open Settings. Enter closes the palette and shows Ran: Open Settings.
  • Clear the input and every command is back. Press Escape and the palette closes with the status unchanged.

Notes

  • Autofocus needs a ref + effect. The input does not exist until the overlay renders, so focus it from a useEffect keyed on open (via a useRef), not inline.
  • filtered is derived, not stored. Compute it from query on each render; do not keep a separate state array in sync.
  • Reset the highlight when the query changes. Otherwise activeIndex can point past the end of a shorter filtered list.
  • Styling (overlay, palette, rows, the kbd chip) is already in styles.css; focus on the state and the keyboard.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium