Gathering detailed insights and metrics for cmdk
Gathering detailed insights and metrics for cmdk
Gathering detailed insights and metrics for cmdk
Gathering detailed insights and metrics for cmdk
npm install cmdk
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
10,005 Stars
145 Commits
288 Forks
24 Watching
4 Branches
47 Contributors
Updated on 28 Nov 2024
Minified
Minified + Gzipped
TypeScript (78.42%)
SCSS (21.36%)
JavaScript (0.15%)
Shell (0.04%)
CSS (0.03%)
Cumulative downloads
Total Downloads
Last day
3.3%
210,523
Compared to previous day
Last week
9.8%
1,172,158
Compared to previous week
Last month
13.8%
4,621,200
Compared to previous month
Last year
753.7%
32,704,946
Compared to previous year
4
1
⌘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?, so you can wrap items in other components or even as static JSX.
Demo and examples: cmdk.paco.me
1pnpm install cmdk
1import { Command } from 'cmdk' 2 3const CommandMenu = () => { 4 return ( 5 <Command label="Command Menu"> 6 <Command.Input /> 7 <Command.List> 8 <Command.Empty>No results found.</Command.Empty> 9 10 <Command.Group heading="Letters"> 11 <Command.Item>a</Command.Item> 12 <Command.Item>b</Command.Item> 13 <Command.Separator /> 14 <Command.Item>c</Command.Item> 15 </Command.Group> 16 17 <Command.Item>Apple</Command.Item> 18 </Command.List> 19 </Command> 20 ) 21}
Or in a dialog:
1import { Command } from 'cmdk' 2 3const CommandMenu = () => { 4 const [open, setOpen] = React.useState(false) 5 6 // Toggle the menu when ⌘K is pressed 7 React.useEffect(() => { 8 const down = (e) => { 9 if (e.key === 'k' && (e.metaKey || e.ctrlKey)) { 10 e.preventDefault() 11 setOpen((open) => !open) 12 } 13 } 14 15 document.addEventListener('keydown', down) 16 return () => document.removeEventListener('keydown', down) 17 }, []) 18 19 return ( 20 <Command.Dialog open={open} onOpenChange={setOpen} label="Global Command Menu"> 21 <Command.Input /> 22 <Command.List> 23 <Command.Empty>No results found.</Command.Empty> 24 25 <Command.Group heading="Letters"> 26 <Command.Item>a</Command.Item> 27 <Command.Item>b</Command.Item> 28 <Command.Separator /> 29 <Command.Item>c</Command.Item> 30 </Command.Group> 31 32 <Command.Item>Apple</Command.Item> 33 </Command.List> 34 </Command.Dialog> 35 ) 36}
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.
[cmdk-root]
Render this to show the command menu inline, or use Dialog to render in a elevated context. Can be controlled with the value
and onValueChange
props.
Note
Values are always trimmed with the trim() method.
1const [value, setValue] = React.useState('apple') 2 3return ( 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)
You can provide a custom filter
function that is called to rank each item. Note that the value will be trimmed.
1<Command 2 filter={(value, search) => { 3 if (value.includes(search)) return 1 4 return 0 5 }} 6/>
A third argument, keywords
, can also be provided to the filter function. Keywords act as aliases for the item value, and can also affect the rank of the item. Keywords are trimmed.
1<Command 2 filter={(value, search, keywords) => { 3 const extendValue = value + ' ' + keywords.join(' ') 4 if (extendValue.includes(search)) return 1 5 return 0 6 }} 7/>
Or disable filtering and sorting entirely:
1<Command shouldFilter={false}> 2 <Command.List> 3 {filteredItems.map((item) => { 4 return ( 5 <Command.Item key={item} value={item}> 6 {item} 7 </Command.Item> 8 ) 9 })} 10 </Command.List> 11</Command>
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:
1<Command loop />
[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 the open
and onOpenChange
props.
1const [open, setOpen] = React.useState(false) 2 3return ( 4 <Command.Dialog open={open} onOpenChange={setOpen}> 5 ... 6 </Command.Dialog> 7)
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.
1const containerElement = React.useRef(null) 2 3return ( 4 <> 5 <Command.Dialog container={containerElement.current} /> 6 <div ref={containerElement} /> 7 </> 8)
[cmdk-input]
All props are forwarded to the underlying input
element. Can be controlled with the value
and onValueChange
props.
1const [search, setSearch] = React.useState('') 2 3return <Command.Input value={search} onValueChange={setSearch} />
[cmdk-list]
Contains items and groups. Animate height using the --cmdk-list-height
CSS variable.
1[cmdk-list] { 2 min-height: 300px; 3 height: var(--cmdk-list-height); 4 max-height: 500px; 5 transition: height 100ms ease; 6}
To scroll item into view earlier near the edges of the viewport, use scroll-padding:
1[cmdk-list] { 2 scroll-padding-block-start: 8px; 3 scroll-padding-block-end: 8px; 4}
[cmdk-item]
[data-disabled?]
[data-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<Command.Item 2 onSelect={(value) => console.log('Selected', value)} 3 // Value is implicity "apple" because of the provided text content 4> 5 Apple 6</Command.Item>
You can also provide a keywords
prop to help with filtering. Keywords are trimmed.
1<Command.Item keywords={['fruit', 'apple']}>Apple</Command.Item>
1<Command.Item 2 onSelect={(value) => console.log('Selected', value)} 3 // Value is implicity "apple" because of the provided text content 4> 5 Apple 6</Command.Item>
You can force an item to always render, regardless of filtering, by passing the forceMount
prop.
[cmdk-group]
[hidden?]
Groups items together with the given heading
([cmdk-group-heading]
).
1<Command.Group heading="Fruit"> 2 <Command.Item>Apple</Command.Item> 3</Command.Group>
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.
You can force a group to always render, regardless of filtering, by passing the forceMount
prop.
[cmdk-separator]
Visible when the search query is empty or alwaysRender
is true, hidden otherwise.
[cmdk-empty]
Automatically renders when there are no results for the search query.
[cmdk-loading]
You should conditionally render this with progress
while loading asynchronous items.
1const [loading, setLoading] = React.useState(false) 2 3return <Command.List>{loading && <Command.Loading>Hang on…</Command.Loading>}</Command.List>
useCommandState(state => state.selectedField)
Hook that composes 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:
1const search = useCommandState((state) => state.search) 2return <Command.Empty>No results found for "{search}".</Command.Empty>
Code snippets for common use cases.
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:
1const ref = React.useRef(null) 2const [open, setOpen] = React.useState(false) 3const [search, setSearch] = React.useState('') 4const [pages, setPages] = React.useState([]) 5const page = pages[pages.length - 1] 6 7return ( 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 27 {page === 'projects' && ( 28 <> 29 <Command.Item>Project A</Command.Item> 30 <Command.Item>Project B</Command.Item> 31 </> 32 )} 33 34 {page === 'teams' && ( 35 <> 36 <Command.Item>Team 1</Command.Item> 37 <Command.Item>Team 2</Command.Item> 38 </> 39 )} 40 </Command.List> 41 </Command> 42)
If your items have nested sub-items that you only want to reveal when searching, render based on the search state:
1const SubItem = (props) => { 2 const search = useCommandState((state) => state.search) 3 if (!search) return null 4 return <Command.Item {...props} /> 5} 6 7return ( 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)
Render the items as they become available. Filtering and sorting will happen automatically.
1const [loading, setLoading] = React.useState(false) 2const [items, setItems] = React.useState([]) 3 4React.useEffect(() => { 5 async function getItems() { 6 setLoading(true) 7 const res = await api.get('/dictionary') 8 setItems(res) 9 setLoading(false) 10 } 11 12 getItems() 13}, []) 14 15return ( 16 <Command> 17 <Command.Input /> 18 <Command.List> 19 {loading && <Command.Loading>Fetching words…</Command.Loading>} 20 {items.map((item) => { 21 return ( 22 <Command.Item key={`word-${item}`} value={item}> 23 {item} 24 </Command.Item> 25 ) 26 })} 27 </Command.List> 28 </Command> 29)
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$ pnpm install @radix-ui/react-popover
Render Command
inside of the popover content:
1import * as Popover from '@radix-ui/react-popover' 2 3return ( 4 <Popover.Root> 5 <Popover.Trigger>Toggle popover</Popover.Trigger> 6 7 <Popover.Content> 8 <Command> 9 <Command.Input /> 10 <Command.List> 11 <Command.Item>Apple</Command.Item> 12 </Command.List> 13 </Command> 14 </Popover.Content> 15 </Popover.Root> 16)
You can find global stylesheets to drop in as a starting point for styling. See website/styles/cmdk for examples.
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.
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.
First, install dependencies and Playwright browsers:
1pnpm install 2pnpm playwright install
Then ensure you've built the library:
1pnpm build
Then run the tests using your local build against real browser engines:
1pnpm test
No vulnerabilities found.
No security vulnerabilities found.