Command
Command (커맨드)
빠르고 조합 가능하며 스타일이 없는 React용 커맨드 메뉴 컴포넌트예요. 명령 팔레트나 검색 메뉴를 만들고 싶을 때 사용해요.
출처: 문서
본문
소개 (About)
<Command /> 컴포넌트는 pacocoursey가 만든 cmdk 컴포넌트를 사용해요.
설치 (Installation)
npx shadcn@latest add command
npm install cmdk
사용법 (Usage)
import {
Command,
CommandDialog,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
CommandShortcut,
} from "@/components/ui/command"
<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
커맨드 메뉴를 다이얼로그로 보여주려면 <CommandDialog /> 컴포넌트를 사용해요.
export function CommandMenu() {
const [open, setOpen] = React.useState(false)
React.useEffect(() => {
const down = (e: KeyboardEvent) => {
if (e.key === "k" && (e.metaKey || e.ctrlKey)) {
e.preventDefault()
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
<Command /> 컴포넌트를 콤보박스로 사용할 수도 있어요. 자세한 내용은 Combobox 페이지를 참고해요.
변경 내역 (Changelog)
2024-10-25 아이콘용 클래스
<CommandItem />에 gap-2 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0를 추가해서 안의 아이콘을 자동으로 스타일링했어요.
command.tsx 파일의 cva 호출에 다음 클래스들을 추가해요.
const CommandItem = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Item
ref={ref}
className={cn(
"... gap-2 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
className
)}
{...props}
/>
))