$npx -y skills add AgentWorkforce/relay --skill implementing-command-palettesUse when building Cmd+K command palettes in React - covers keyboard navigation with arrow keys, keeping selected items in view with scrollIntoView, filtering with shortcut matching, and preventing infinite re-renders from reference instability
| 1 | # Implementing Command Palettes |
| 2 | |
| 3 | ## Overview |
| 4 | |
| 5 | Command palettes (Cmd+K / Ctrl+K) need precise keyboard navigation, scroll behavior, and stable references to avoid re-render loops. This skill covers the mechanical patterns that make command palettes feel responsive. |
| 6 | |
| 7 | ## When to Use |
| 8 | |
| 9 | - Building a Cmd+K command palette in React |
| 10 | - Implementing arrow key navigation with visual selection |
| 11 | - Keeping selected items visible during keyboard navigation |
| 12 | - Filtering commands by label text AND keyboard shortcuts |
| 13 | - Experiencing infinite re-renders when commands update |
| 14 | |
| 15 | ## Quick Reference |
| 16 | |
| 17 | | Feature | Implementation | |
| 18 | | ----------------- | ---------------------------------------------------------- | |
| 19 | | Arrow navigation | Track `selectedIndex`, clamp with `Math.min/max` | |
| 20 | | Keep in view | `scrollIntoView({ block: 'nearest', behavior: 'smooth' })` | |
| 21 | | Shortcut matching | Strip spaces from shortcuts, match against query | |
| 22 | | Stable icons | Define icon elements outside component | |
| 23 | | Stable handlers | `useCallback` + `noop` constant for disabled states | |
| 24 | |
| 25 | ## Keyboard Navigation |
| 26 | |
| 27 | ### Critical: Wrapper Pattern for Conditional Rendering |
| 28 | |
| 29 | **This is the most common source of bugs.** The keyboard effect must ONLY run when the palette is open. Use a wrapper component: |
| 30 | |
| 31 | ```tsx |
| 32 | // Wrapper ensures effects only run when open |
| 33 | export function CommandPalette(props: CommandPaletteProps) { |
| 34 | if (!props.isOpen) return null; |
| 35 | return <CommandPaletteContent {...props} />; |
| 36 | } |
| 37 | |
| 38 | // Content component - effects run on mount/unmount |
| 39 | function CommandPaletteContent({ onClose, ... }: CommandPaletteProps) { |
| 40 | // Effects here only run when palette is visible |
| 41 | useEffect(() => { |
| 42 | const handleKeyDown = (e: KeyboardEvent) => { ... }; |
| 43 | window.addEventListener('keydown', handleKeyDown); |
| 44 | return () => window.removeEventListener('keydown', handleKeyDown); |
| 45 | }, [deps]); |
| 46 | |
| 47 | return <div>...</div>; |
| 48 | } |
| 49 | ``` |
| 50 | |
| 51 | **Why this matters:** |
| 52 | |
| 53 | - If you put `if (!isOpen) return null` AFTER useEffect hooks, the effects still run when closed |
| 54 | - This causes keyboard listeners to be registered even when palette is invisible |
| 55 | - The wrapper pattern ensures effects only run when the component actually renders |
| 56 | |
| 57 | ### Input Focus + Window Listener Pattern |
| 58 | |
| 59 | The input MUST be focused (for typing to work), and keyboard navigation MUST use `window.addEventListener`. This works because: |
| 60 | |
| 61 | - The window listener receives keydown events for ALL keys |
| 62 | - Arrow keys don't insert text into inputs, so `e.preventDefault()` just stops page scrolling |
| 63 | - Regular character keys still reach the input for typing |
| 64 | |
| 65 | ```tsx |
| 66 | // Input with autoFocus - NOT setTimeout focus |
| 67 | <input |
| 68 | autoFocus |
| 69 | type="text" |
| 70 | value={query} |
| 71 | onChange={(e) => { |
| 72 | setQuery(e.target.value); |
| 73 | setSelectedIndex(0); // Reset to first item when query changes |
| 74 | }} |
| 75 | /> |
| 76 | ``` |
| 77 | |
| 78 | ### Index Management |
| 79 | |
| 80 | ```tsx |
| 81 | const [selectedIndex, setSelectedIndex] = useState(0); |
| 82 | |
| 83 | useEffect(() => { |
| 84 | if (!isOpen) return; |
| 85 | |
| 86 | const handleKeyDown = (e: KeyboardEvent) => { |
| 87 | switch (e.key) { |
| 88 | case 'ArrowDown': |
| 89 | e.preventDefault(); |
| 90 | // Clamp to last item |
| 91 | setSelectedIndex((prev) => Math.min(prev + 1, filteredItems.length - 1)); |
| 92 | break; |
| 93 | case 'ArrowUp': |
| 94 | e.preventDefault(); |
| 95 | // Clamp to first item |
| 96 | setSelectedIndex((prev) => Math.max(prev - 1, 0)); |
| 97 | break; |
| 98 | case 'Enter': |
| 99 | e.preventDefault(); |
| 100 | if (filteredItems[selectedIndex]) { |
| 101 | executeCommand(filteredItems[selectedIndex]); |
| 102 | close(); |
| 103 | } |
| 104 | break; |
| 105 | case 'Escape': |
| 106 | e.preventDefault(); |
| 107 | close(); |
| 108 | break; |
| 109 | } |
| 110 | }; |
| 111 | |
| 112 | // NO capture phase needed - simple window listener works with focused input |
| 113 | window.addEventListener('keydown', handleKeyDown); |
| 114 | return () => window.removeEventListener('keydown', handleKeyDown); |
| 115 | }, [isOpen, filteredItems, selectedIndex, close]); |
| 116 | ``` |
| 117 | |
| 118 | **Key patterns:** |
| 119 | |
| 120 | - `e.preventDefault()` stops arrow keys from scrolling the page |
| 121 | - `Math.min/max` prevents index going out of bounds |
| 122 | - Effect depends on `filteredItems` so navigation updates when filter changes |
| 123 | - Use `autoFocus` on input, NOT `setTimeout(() => ref.current?.focus(), 0)` |
| 124 | |
| 125 | ## Keeping Selected Item in View |
| 126 | |
| 127 | ### Using Refs Array |
| 128 | |
| 129 | ```tsx |
| 130 | const itemRefs = useRef<(HTMLButtonElement | null)[]>([]); |
| 131 | |
| 132 | // Scroll effect - runs when selection changes |
| 133 | useEffect(() => { |
| 134 | const selectedItem = itemRefs.current[selectedIndex]; |
| 135 | if (selectedItem) { |
| 136 | selectedItem.scrollIntoView({ |
| 137 | block: 'nearest', // Minimal scroll - only scroll if needed |
| 138 | behavior: 'smooth', // Smooth animation |
| 139 | }); |
| 140 | } |
| 141 | }, [selectedIn |