Command
A searchable list of actions and pages, shown inline or in a dialog, that people drive from the keyboard.
Installation
pnpm dlx shadcn@latest add @silkware/commandTo copy the component by hand, install its dependencies:
pnpm add react-aria-components cn lucide-reactThen copy the source into components/ui/command.tsx. It also needs Dialog and Input Group:
"use client"
import * as React from "react"import { cn } from "cn"import { Autocomplete, Collection, composeRenderProps, Header, Input, Menu, MenuItem, MenuSection, OverlayTriggerStateContext, SearchField, Separator, useFilter, type AutocompleteProps, type InputProps, type MenuItemProps, type MenuProps, type MenuSectionProps, type SeparatorProps,} from "@animate-ui/react/primitives/react-aria"
import { Dialog, DialogDescription, DialogHeader, DialogTitle,} from "@/components/ui/dialog"import { InputGroup, InputGroupAddon,} from "@/components/ui/input-group"import { SearchIcon, CheckIcon } from "lucide-react"
function Command({ className, dir, style, ...props}: Omit<AutocompleteProps, "className" | "style"> & { className?: string dir?: React.HTMLAttributes<HTMLDivElement>["dir"] style?: React.CSSProperties}) { const { contains } = useFilter({ sensitivity: "base" }) return ( <div data-slot="command" dir={dir} className={cn( "flex size-full flex-col overflow-hidden rounded-xl! bg-popover p-1 text-popover-foreground", className )} style={style} > <Autocomplete {...props} filter={props.filter || contains}> {props.children} </Autocomplete> </div> )}
function CommandDialog({ title = "Command Palette", description = "Search for a command to run...", children, open, onOpenChange, className, showCloseButton = false, ...props}: Omit< React.ComponentProps<typeof Dialog>, "children" | "className" | "isOpen" | "onOpenChange"> & { title?: string description?: string open?: boolean onOpenChange?: (isOpen: boolean) => void className?: string showCloseButton?: boolean children: React.ReactNode}) { return ( <Dialog isOpen={open} onOpenChange={onOpenChange} className={cn( "top-1/3 translate-y-0 overflow-hidden rounded-xl! p-0", className )} showCloseButton={showCloseButton} isDismissable {...props} > <DialogHeader className="sr-only"> <DialogTitle>{title}</DialogTitle> <DialogDescription>{description}</DialogDescription> </DialogHeader> {children} </Dialog> )}
function CommandInput({ className, ...props }: InputProps) { const inOverlay = React.useContext(OverlayTriggerStateContext) !== null return ( <SearchField autoFocus={inOverlay} aria-label={props.placeholder || "Search"} data-slot="command-input-wrapper" className="p-1 pb-0" > <InputGroup className="h-8! rounded-lg! border-input/30 bg-input/30 shadow-none! *:data-[slot=input-group-addon]:pl-2!"> <Input {...props} data-slot="command-input" className={cn( "w-full text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50 [&::-webkit-search-cancel-button]:hidden", className )} /> <InputGroupAddon> <SearchIcon className="size-4 shrink-0 opacity-50" /> </InputGroupAddon> </InputGroup> </SearchField> )}
function CommandList<T extends object>({ className, ...props }: MenuProps<T>) { return ( <Menu {...props} data-slot="command-list" className={cn( "no-scrollbar max-h-72 scroll-py-1 overflow-x-hidden overflow-y-auto outline-none", className )} /> )}
function CommandEmpty({ className, ...props }: React.ComponentProps<"div">) { return ( <div data-slot="command-empty" className={cn("py-6 text-center text-sm", className)} {...props} /> )}
function CommandGroup<T extends object>({ className, children, items, heading, ...props}: MenuSectionProps<T> & { heading?: string }) { return ( <MenuSection data-slot="command-group" className={cn( "overflow-hidden p-1 text-foreground **:[[cmdk-group-heading]]:px-2 **:[[cmdk-group-heading]]:py-1.5 **:[[cmdk-group-heading]]:text-xs **:[[cmdk-group-heading]]:font-medium **:[[cmdk-group-heading]]:text-muted-foreground", className )} {...props} > {heading && <Header cmdk-group-heading="">{heading}</Header>} <Collection items={items}>{children}</Collection> </MenuSection> )}
function CommandSeparator({ className, ...props }: SeparatorProps) { return ( <Separator data-slot="command-separator" className={cn("-mx-1 h-px w-auto bg-border", className)} {...props} /> )}
function CommandItem<T extends object>({ className, children, textValue, ...props}: MenuItemProps<T>) { return ( <MenuItem {...props} data-slot="command-item" className={cn( "group/command-item relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none in-data-[slot=dialog-content]:rounded-lg! data-focused:bg-muted data-focused:text-foreground data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-muted data-selected:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-focused:**:[svg]:text-foreground data-selected:**:[svg]:text-foreground", className )} textValue={ textValue || (typeof children === "string" ? children : undefined) } > {composeRenderProps(children, (children) => ( <> {children} <CheckIcon className="ml-auto opacity-0 group-has-data-[slot=command-shortcut]/command-item:hidden group-data-[checked=true]/command-item:opacity-100" /> </> ))} </MenuItem> )}
function CommandShortcut({ className, ...props}: React.ComponentProps<"span">) { return ( <span data-slot="command-shortcut" className={cn( "ml-auto text-xs tracking-widest text-muted-foreground group-data-focused/command-item:text-foreground group-data-selected/command-item:text-foreground", className )} {...props} /> )}
export { Command, CommandDialog, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem, CommandShortcut, CommandSeparator,}Usage
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList,} from "@/components/ui/command"<Command> <CommandInput placeholder="Search actions" /> <CommandList aria-label="Actions" renderEmptyState={() => <CommandEmpty>No results found.</CommandEmpty>} > <CommandGroup heading="Orders"> <CommandItem>New purchase order</CommandItem> <CommandItem>Approve pending orders</CommandItem> </CommandGroup> </CommandList></Command>Command is a React Aria Autocomplete that filters its list as people type into the input. The list is a React Aria Menu, so items are actions, not options: each item runs onAction (set on the list or on the item) or follows an href. Nothing is selected or stored. Give the list an aria-label, and give items that hold more than plain text a textValue, because that text is what the filter matches.
The site's own search, opened with Ctrl K or ⌘ K, is a CommandDialog with items that carry an href. Command does not register that shortcut. Add the key listener where you own the page, and close the dialog from onAction.
Examples
Dialog
CommandDialog shows the command menu in a modal dialog. Control it with open and onOpenChange, give it a title and description for screen readers (they are visually hidden), and close it from the list's onAction.
Groups
Put related items under a CommandGroup with a heading, and separate sections with CommandSeparator. Filtering hides groups with no match.
Shortcuts
CommandShortcut pushes a hint of the key combination to the end of the row. It is text only: the shortcut itself has to be registered by your application.
Links
Give an item an href to navigate. Internal paths go through the router, as with Button used as a link. Use textValue to widen what the filter matches, for example a page title plus its keywords.
Disabled
isDisabled on an item keeps it in the list but removes it from keyboard navigation and ignores it on press.
Accessibility
| Key | Action |
|---|---|
| ArrowDown | Moves focus to the next item. Focus stays in the input. |
| ArrowUp | Moves focus to the previous item. |
| Enter | Runs the focused item. |
| Escape | Clears the search text. When the text is already empty, closes the dialog when the menu is in one. |
React Aria provides:
- A search input that keeps focus while the list is navigated with the arrow keys, announced through
aria-activedescendant. - A list with the
menurole andmenuitemitems, grouped withgroupand a heading. - Live announcements of how many results match as people type.
- In
CommandDialog, a modal dialog that traps focus, closes on Escape and returns focus to the control that opened it.
You provide:
- An
aria-labelonCommandList, and atitleanddescriptiononCommandDialog. - A
textValueon every item that is not a plain string. - A
renderEmptyStateso an empty search says so. - A way to open the dialog from the keyboard, usually a shortcut, and a visible button for people who do not use it.
Guidelines
When to use
- As a quick way to reach actions and pages in an application with many of them.
- For frequent actions that already have a place in the interface but are slow to reach.
- Inline, as a searchable list of actions inside a popover or a panel.
When not to use
- To choose a value in a form. Use a Select or a Combobox.
- For a short list of actions on one object. Use a Dropdown Menu.
- As the only way to reach a function. Every action must also exist in the interface.
- For site navigation that people scan. Use a Navigation Menu or a Sidebar.
Content
- Start each action with a verb and name the object: "Approve order", "Export order list".
- Name pages by their title, as they appear in navigation.
- Put the headings in plain nouns: "Orders", "Suppliers".
- Keep items to one line. Add a shortcut only when the shortcut really exists.
Naming actions
Name actions with a verb and the object they act on.
Don’t use vague nouns or catch-all headings. People search by what they want to do.
API reference
Command
The container. It renders a <div> with the surface styles around a React Aria Autocomplete and accepts its props. Without a filter, it uses a case-insensitive "contains" match.
| Prop | Type | Default | Description |
|---|---|---|---|
filter? | (textValue: string, inputValue: string) => boolean | None | Decides whether an item matches the text typed. Defaults to a case-insensitive contains match. |
inputValue? | string | None | The search text, for a controlled menu. |
onInputChange? | (value: string) => void | None | Called when the search text changes. |
dir? | "ltr" | "rtl" | None | The text direction of the surface. |
className? | string | None | Classes merged onto the container. |
CommandDialog
The menu inside a modal Dialog, pinned near the top of the screen. The title and description are visually hidden.
| Prop | Type | Default | Description |
|---|---|---|---|
open? | boolean | None | Whether the dialog is open. |
onOpenChange? | (isOpen: boolean) => void | None | Called when the dialog opens or closes. |
title? | string | "Command Palette" | The accessible name of the dialog. |
description? | string | "Search for a command to run..." | The accessible description of the dialog. |
showCloseButton? | boolean | false | Shows a close button in the corner. |
className? | string | None | Classes merged onto the dialog. |
CommandInput
The search field with a search icon. It takes focus when it appears inside a dialog or popover, and not on page load when the command sits in the page. It accepts the props of the React Aria Input. Its aria-label is the placeholder, or "Search".
CommandList
The list, a React Aria Menu. It scrolls past 18rem.
| Prop | Type | Default | Description |
|---|---|---|---|
onAction? | (key: Key) => void | None | Called with the id of the item that was run. |
renderEmptyState? | () => ReactNode | None | What to show when no item matches the search. |
aria-label? | string | None | The accessible name of the list. |
CommandItem
One action, a React Aria MenuItem.
| Prop | Type | Default | Description |
|---|---|---|---|
id? | Key | None | Identifies the item in onAction. Set it when the children are not a plain string. |
textValue? | string | None | The text the filter matches and screen readers read. Defaults to the children when they are a string. |
href? | string | None | Makes the item a link to this destination. |
onAction? | () => void | None | Called when the item is run. |
isDisabled? | boolean | false | Removes the item from keyboard navigation and ignores presses. |
CommandGroup
A section of items, a React Aria MenuSection. Pass heading for the title, and items with a render function to build the group from data.
CommandEmpty, CommandSeparator and CommandShortcut
CommandEmpty is the centred message for an empty result, CommandSeparator a divider between groups, and CommandShortcut the muted text at the end of an item for a key combination.