CmdK

Fast, unstyled command menu React component.

README


⌘K cmdk minzip package size cmdk package version


⌘K is a command menu React component that can also be used as an accessible combobox. You render items, it filters and sorts them automatically. ⌘K supports a fully composable API [How?](/ARCHITECTURE.md), so you can wrap items in other components or even as static JSX.

Demo and examples: cmdk.paco.me

Install


  1. ``` sh
  2. npm install cmdk
  3. ```

Use


  1. ```tsx
  2. import { Command } from 'cmdk'

  3. const CommandMenu = () => {
  4.   return (
  5.     <Command label="Command Menu">
  6.       <Command.Input />
  7.       <Command.List>
  8.         <Command.Empty>No results found.</Command.Empty>
  9. <Command.Group heading="Letters">
  10.           <Command.Item>a</Command.Item>
  11.           <Command.Item>b</Command.Item>
  12.           <Command.Separator />
  13.           <Command.Item>c</Command.Item>
  14.         </Command.Group>
  15. <Command.Item>Apple</Command.Item>
  16.       </Command.List>
  17.     </Command>
  18.   )
  19. }
  20. ```

Or in a dialog:

  1. ```tsx
  2. import { Command } from 'cmdk'

  3. const CommandMenu = () => {
  4.   const [open, setOpen] = React.useState(false)

  5.   // Toggle the menu when ⌘K is pressed
  6.   React.useEffect(() => {
  7.     const down = (e) => {
  8.       if (e.key === 'k' && e.metaKey) {
  9.         setOpen((open) => !open)
  10.       }
  11.     }

  12.     document.addEventListener('keydown', down)
  13.     return () => document.removeEventListener('keydown', down)
  14.   }, [])

  15.   return (
  16.     <Command.Dialog open={open} onOpenChange={setOpen} label="Global Command Menu">
  17.       <Command.Input />
  18.       <Command.List>
  19.         <Command.Empty>No results found.</Command.Empty>
  20. <Command.Group heading="Letters">
  21.           <Command.Item>a</Command.Item>
  22.           <Command.Item>b</Command.Item>
  23.           <Command.Separator />
  24.           <Command.Item>c</Command.Item>
  25.         </Command.Group>
  26. <Command.Item>Apple</Command.Item>
  27.       </Command.List>
  28.     </Command.Dialog>
  29.   )
  30. }
  31. ```

Parts and styling


All parts forward props, including ref, to an appropriate element. Each part has a specific data-attribute (starting with cmdk-) that can be used for styling.

Command [cmdk-root]


Render this to show the command menu inline, or use Dialog to render in a elevated context. Can be controlled with thevalue and onValueChange props.

Note

>

Values are always converted to lowercase and trimmed. Use apple, not Apple.


  1. ```tsx
  2. const [value, setValue] = React.useState('apple')

  3. return (
  4.   <Command value={value} onValueChange={setValue}>
  5.     <Command.Input />
  6.     <Command.List>
  7.       <Command.Item>Orange</Command.Item>
  8.       <Command.Item>Apple</Command.Item>
  9.     </Command.List>
  10.   </Command>
  11. )
  12. ```

You can provide a custom filter function that is called to rank each item. Both strings are normalized as lowercase and trimmed.

  1. ```tsx
  2. <Command
  3.   filter={(value, search) => {
  4.     if (value.includes(search)) return 1
  5.     return 0
  6.   }}
  7. />
  8. ```

Or disable filtering and sorting entirely:

  1. ```tsx
  2. <Command shouldFilter={false}>
  3.   <Command.List>
  4.     {filteredItems.map((item) => {
  5.       return (
  6.         <Command.Item key={item} value={item}>
  7.           {item}
  8.         </Command.Item>
  9.       )
  10.     })}
  11.   </Command.List>
  12. </Command>
  13. ```

You can make the arrow keys wrap around the list (when you reach the end, it goes back to the first item) by setting the loop prop:


Dialog [cmdk-dialog] [cmdk-overlay]


Props are forwarded to Command. Composes Radix UI's Dialog component. The overlay is always rendered. See the Radix Documentation for more information. Can be controlled with theopen and onOpenChange props.

  1. ```tsx
  2. const [open, setOpen] = React.useState(false)

  3. return (
  4.   <Command.Dialog open={open} onOpenChange={setOpen}>
  5.     ...
  6.   </Command.Dialog>
  7. )
  8. ```

You can provide a container prop that accepts an HTML element that is forwarded to Radix UI's Dialog Portal component to specify which element the Dialog should portal into (defaults to body). See the Radix Documentation for more information.

  1. ```tsx
  2. const containerElement = React.useRef(null)

  3. return (
  4.   <>
  5.     <Command.Dialog container={containerElement.current} />
  6.     <div ref={containerElement} />
  7.   </>
  8. )
  9. ```

Input [cmdk-input]


All props are forwarded to the underlying input element. Can be controlled with the value and onValueChange props.

  1. ```tsx
  2. const [search, setSearch] = React.useState('')

  3. return <Command.Input value={search} onValueChange={setSearch} />
  4. ```

List [cmdk-list]


Contains items and groups. Animate height using the --cmdk-list-height CSS variable.

  1. ```css
  2. [cmdk-list] {
  3.   min-height: 300px;
  4.   height: var(--cmdk-list-height);
  5.   max-height: 500px;
  6.   transition: height 100ms ease;
  7. }
  8. ```

To scroll item into view earlier near the edges of the viewport, use scroll-padding:

  1. ```css
  2. [cmdk-list] {
  3.   scroll-padding-block-start: 8px;
  4.   scroll-padding-block-end: 8px;
  5. }
  6. ```

Item [cmdk-item] [aria-disabled?] [aria-selected?]


Item that becomes active on pointer enter. You should provide a unique value for each item, but it will be automatically inferred from the .textContent.

  1. ```tsx
  2. <Command.Item
  3.   onSelect={(value) => console.log('Selected', value)}
  4.   // Value is implicity "apple" because of the provided text content
  5. >
  6.   Apple
  7. </Command.Item>
  8. ```

Group [cmdk-group] [hidden?]


Groups items together with the given heading ([cmdk-group-heading]).

  1. ```tsx
  2. <Command.Group heading="Fruit">
  3.   <Command.Item>Apple</Command.Item>
  4. </Command.Group>
  5. ```

Groups will not unmount from the DOM, rather the hidden attribute is applied to hide it from view. This may be relevant in your styling.

Separator [cmdk-separator]


Visible when the search query is empty or alwaysRender is true, hidden otherwise.

Empty [cmdk-empty]


Automatically renders when there are no results for the search query.

Loading [cmdk-loading]


You should conditionally render this with progress while loading asynchronous items.

  1. ```tsx
  2. const [loading, setLoading] = React.useState(false)

  3. return <Command.List>{loading && <Command.Loading>Hang on</Command.Loading>}Command.List>
  4. ```

useCommandState(state => state.selectedField)


Hook that composes [useSyncExternalStore](https://reactjs.org/docs/hooks-reference.html#usesyncexternalstore). Pass a function that returns a slice of the command menu state to re-render when that slice changes. This hook is provided for advanced use cases and should not be commonly used.

A good use case would be to render a more detailed empty state, like so:

  1. ```tsx
  2. const search = useCommandState((state) => state.search)
  3. return <Command.Empty>No results found for "{search}".</Command.Empty>
  4. ```

Examples


Code snippets for common use cases.

Nested items


Often selecting one item should navigate deeper, with a more refined set of items. For example selecting "Change theme…" should show new items "Dark theme" and "Light theme". We call these sets of items "pages", and they can be implemented with simple state:

  1. ```tsx
  2. const ref = React.useRef(null)
  3. const [open, setOpen] = React.useState(false)
  4. const [search, setSearch] = React.useState('')
  5. const [pages, setPages] = React.useState([])
  6. const page = pages[pages.length - 1]

  7. return (
  8.   <Command
  9.     onKeyDown={(e) => {
  10.       // Escape goes to previous page
  11.       // Backspace goes to previous page when search is empty
  12.       if (e.key === 'Escape' || (e.key === 'Backspace' && !search)) {
  13.         e.preventDefault()
  14.         setPages((pages) => pages.slice(0, -1))
  15.       }
  16.     }}
  17.   >
  18.     <Command.Input value={search} onValueChange={setSearch} />
  19.     <Command.List>
  20.       {!page && (
  21.         <>
  22.           <Command.Item onSelect={() => setPages([...pages, 'projects'])}>Search projects</Command.Item>
  23.           <Command.Item onSelect={() => setPages([...pages, 'teams'])}>Join a team</Command.Item>
  24.         </>
  25.       )}

  26.       {page === 'projects' && (
  27.         <>
  28.           <Command.Item>Project A</Command.Item>
  29.           <Command.Item>Project B</Command.Item>
  30.         </>
  31.       )}

  32.       {page === 'teams' && (
  33.         <>
  34.           <Command.Item>Team 1</Command.Item>
  35.           <Command.Item>Team 2</Command.Item>
  36.         </>
  37.       )}
  38.     </Command.List>
  39.   </Command>
  40. )
  41. ```

Show sub-items when searching


If your items have nested sub-items that you only want to reveal when searching, render based on the search state:

  1. ```tsx
  2. const SubItem = (props) => {
  3.   const search = useCommandState((state) => state.search)
  4.   if (!search) return null
  5.   return <Command.Item {...props} />
  6. }

  7. return (
  8.   <Command>
  9.     <Command.Input />
  10.     <Command.List>
  11.       <Command.Item>Change theme</Command.Item>
  12.       <SubItem>Change theme to dark</SubItem>
  13.       <SubItem>Change theme to light</SubItem>
  14.     </Command.List>
  15.   </Command>
  16. )
  17. ```

Asynchronous results


Render the items as they become available. Filtering and sorting will happen automatically.

  1. ```tsx
  2. const [loading, setLoading] = React.useState(false)
  3. const [items, setItems] = React.useState([])

  4. React.useEffect(() => {
  5.   async function getItems() {
  6.     setLoading(true)
  7.     const res = await api.get('/dictionary')
  8.     setItems(res)
  9.     setLoading(false)
  10.   }

  11.   getItems()
  12. }, [])

  13. return (
  14.   <Command>
  15.     <Command.Input />
  16.     <Command.List>
  17.       {loading && <Command.Loading>Fetching words</Command.Loading>}
  18.       {items.map((item) => {
  19.         return (
  20.           <Command.Item key={`word-${item}`} value={item}>
  21.             {item}
  22.           </Command.Item>
  23.         )
  24.       })}
  25.     </Command.List>
  26.   </Command>
  27. )
  28. ```

Use inside Popover


We recommend using the Radix UI popover component. ⌘K relies on the Radix UI Dialog component, so this will reduce your bundle size a bit due to shared dependencies.

  1. ``` sh
  2. $ npm install @radix-ui/react-popover
  3. ```

Render Command inside of the popover content:

  1. ```tsx
  2. import * as Popover from '@radix-ui/react-popover'

  3. return (
  4.   <Popover.Root>
  5.     <Popover.Trigger>Toggle popover</Popover.Trigger>
  6. <Popover.Content>
  7.       <Command>
  8.         <Command.Input />
  9.         <Command.List>
  10.           <Command.Item>Apple</Command.Item>
  11.         </Command.List>
  12.       </Command>
  13.     </Popover.Content>
  14.   </Popover.Root>
  15. )
  16. ```

Drop in stylesheets


You can find global stylesheets to drop in as a starting point for styling. See website/styles/cmdk for examples.

FAQ


Accessible? Yes. Labeling, aria attributes, and DOM ordering tested with Voice Over and Chrome DevTools. Dialog composes an accessible Dialog implementation.

Virtualization? No. Good performance up to 2,000-3,000 items, though. Read below to bring your own.

Filter/sort items manually? Yes. Pass shouldFilter={false} to Command. Better memory usage and performance. Bring your own virtualization this way.

React 18 safe? Yes, required. Uses React 18 hooks like useId and useSyncExternalStore.

Unstyled? Yes, use the listed CSS selectors.

Hydration mismatch? No, likely a bug in your code. Ensure the open prop to Command.Dialog is false on the server.

React strict mode safe? Yes. Open an issue if you notice an issue.

Weird/wrong behavior? Make sure your Command.Item has a key and unique value.

Concurrent mode safe? Maybe, but concurrent mode is not yet real. Uses risky approaches like manual DOM ordering.

React server component? No, it's a client component.

Listen for ⌘K automatically? No, do it yourself to have full control over keybind context.

React Native? No, and no plans to support it. If you build a React Native version, let us know and we'll link your repository here.

History


Written in 2019 by Paco (@pacocoursey) to see if a composable combobox API was possible. Used for the Vercel command menu and autocomplete by Rauno (@raunofreiberg) in 2020. Re-written independently in 2022 with a simpler and more performant approach. Ideas and help from Shu (@shuding\_).

use-descendants was extracted from the 2019 version.