Files
shadcn-ui/apps/www/content/docs/primitives/command.mdx
2023-02-08 07:48:13 +04:00

130 lines
3.1 KiB
Plaintext

---
title: Command
description: Fast, composable, unstyled command menu for React.
component: true
---
<Callout>
The `<Command />` component is built using [`cmdk`](https://cmdk.paco.me) by
[pacocoursey](https://twitter.com/pacocoursey) and
[raunofreiberg](https://twitter.com/raunofreiberg). Check out https://cmdk.paco.me.
</Callout>
<ComponentExample src="/components/examples/command/demo.tsx" align="start">
<CommandDemo />
</ComponentExample>
## Installation
1. Install the `cmdk` package:
```bash
npm install cmdk
```
2. The `<Command />` component depends on the `<Dialog />` component. Follow the [Dialog installation instructions](/docs/primitives/dialog#installation).
3. Copy and paste the following code into your project.
<ComponentSource src="/components/ui/command.tsx" />
<Callout>
This is the `<Command />` primitive. You can place it in a file at
`components/ui/command.tsx`.
</Callout>
## Usage
```tsx
import {
CommandDialog,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
CommandShortcut,
} from "@/components/ui/command"
```
```tsx
<Command>
<CommandInput placeholder="Type a command or search..." />
<CommandList>
<CommandEmpty>No results found.</CommandEmpty>
<CommandGroup heading="Suggestions">
<CommandItem>Calendar</CommandItem>
<CommandItem>Search Emoji</CommandItem>
<CommandItem>Calculator</CommandItem>
</CommandGroup>
<CommandSeparator />
<CommandGroup heading="Settings">
<CommandItem>Profile</CommandItem>
<CommandItem>Billing</CommandItem>
<CommandItem>Settings</CommandItem>
</CommandGroup>
</CommandList>
</Command>
```
## Examples
### Dialog
<ComponentExample src="/components/examples/command/dialog.tsx">
<CommandDialogDemo />
</ComponentExample>
To show the command menu in a dialog, use the `<CommandDialog />` component.
```tsx
export function CommandMenu() {
const [open, setOpen] = React.useState(false)
React.useEffect(() => {
const down = (e: KeyboardEvent) => {
if (e.key === "k" && e.metaKey) {
setOpen((open) => !open)
}
}
document.addEventListener("keydown", down)
return () => document.removeEventListener("keydown", down)
}, [])
return (
<CommandDialog open={open} onOpenChange={setOpen}>
<CommandInput placeholder="Type a command or search..." />
<CommandList>
<CommandEmpty>No results found.</CommandEmpty>
<CommandGroup heading="Suggestions">
<CommandItem>Calendar</CommandItem>
<CommandItem>Search Emoji</CommandItem>
<CommandItem>Calculator</CommandItem>
</CommandGroup>
</CommandList>
</CommandDialog>
)
}
```
### Combobox
<ComponentExample src="/components/examples/command/combobox.tsx">
<CommandCombobox />
</ComponentExample>
### Popover
<ComponentExample src="/components/examples/command/popover.tsx">
<CommandPopover />
</ComponentExample>
### Dropdown menu
<ComponentExample src="/components/examples/command/dropdown-menu.tsx">
<CommandDropdownMenu />
</ComponentExample>