Dropdown Menu
Opens a list of actions from a button, for commands that do not need a place of their own on the page.
Installation
pnpm dlx shadcn@latest add @silkware/dropdown-menuTo copy the component by hand, install its dependencies:
pnpm add react-aria-components class-variance-authority cn lucide-reactThen copy the source into components/ui/dropdown-menu.tsx:
"use client"
import * as React from "react"import { cva } from "class-variance-authority"import { cn } from "cn"import { composeRenderProps, Header as HeaderPrimitive, MenuItem as MenuItemPrimitive, Menu as MenuPrimitive, MenuSection as MenuSectionPrimitive, MenuTrigger as MenuTriggerPrimitive, Popover as PopoverPrimitive, Separator as SeparatorPrimitive, SubmenuTrigger as SubmenuTriggerPrimitive, type MenuItemProps as MenuItemPrimitiveProps, type MenuSectionProps as MenuSectionPrimitiveProps,} from "@animate-ui/react/primitives/react-aria"import { CheckIcon, ChevronRightIcon } from "lucide-react"
function DropdownMenuTrigger({ ...props}: React.ComponentProps<typeof MenuTriggerPrimitive>) { return <MenuTriggerPrimitive data-slot="dropdown-menu-trigger" {...props} />}
function DropdownMenu({ "data-slot": dataSlot = "dropdown-menu-content", placement = "bottom start", offset = 4, crossOffset = 0, className, children, ...props}: Omit< React.ComponentProps<typeof MenuPrimitive<object>>, "children" | "className"> & Pick< React.ComponentProps<typeof PopoverPrimitive>, "placement" | "offset" | "crossOffset" > & { "data-slot"?: string className?: string children?: React.ReactNode }) { return ( <PopoverPrimitive data-slot={dataSlot} placement={placement} offset={offset} crossOffset={crossOffset} className={cn("z-50 w-(--trigger-width) min-w-32 origin-(--trigger-anchor-point) overflow-x-hidden overflow-y-auto rounded-md bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-none data-exiting:overflow-hidden **:data-[slot$=-item]:data-focused:bg-foreground/10", className )} > <MenuPrimitive className="max-h-[inherit] overflow-x-hidden overflow-y-auto outline-hidden" {...props} > {children} </MenuPrimitive> </PopoverPrimitive> )}
function DropdownMenuGroup({ ...props}: Omit<MenuSectionPrimitiveProps<object>, "children"> & { children?: React.ReactNode}) { return <MenuSectionPrimitive data-slot="dropdown-menu-group" {...props} />}
function DropdownMenuLabel({ className, inset, ...props}: React.ComponentProps<typeof HeaderPrimitive> & { inset?: boolean}) { return ( <HeaderPrimitive data-slot="dropdown-menu-label" data-inset={inset} className={cn( "px-2 py-1.5 text-xs font-medium text-muted-foreground data-inset:pl-8", className )} {...props} /> )}
const dropdownMenuItemVariants = cva( "group/dropdown-menu-item relative flex cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0", { variants: { selectionMode: { none: "gap-2 rounded-sm px-2 py-1.5 text-sm focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive", single: "gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-8 [&_svg:not([class*='size-'])]:size-4", multiple: "gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-8 [&_svg:not([class*='size-'])]:size-4", }, }, })
function DropdownMenuItem({ className, inset, variant = "default", children, ...props}: MenuItemPrimitiveProps<object> & { inset?: boolean variant?: "default" | "destructive"}) { return ( <MenuItemPrimitive data-slot="dropdown-menu-item" data-inset={inset} data-variant={variant} textValue={typeof children === "string" ? children : props.textValue} className={composeRenderProps(className, (className, { selectionMode }) => cn(dropdownMenuItemVariants({ selectionMode }), className) )} {...props} > {composeRenderProps( children, (children, { isSelected, selectionMode }) => ( <> {selectionMode !== "none" ? ( <span className="pointer-events-none absolute right-2 flex items-center justify-center" data-slot={ selectionMode === "single" ? "dropdown-menu-radio-item-indicator" : "dropdown-menu-checkbox-item-indicator" } > {isSelected ? ( <CheckIcon /> ) : null} </span> ) : null} {children} </> ) )} </MenuItemPrimitive> )}
function DropdownMenuSub({ ...props}: React.ComponentProps<typeof SubmenuTriggerPrimitive>) { return <SubmenuTriggerPrimitive data-slot="dropdown-menu-sub" {...props} />}
function DropdownMenuSubTrigger({ className, inset, children, ...props}: MenuItemPrimitiveProps<object> & { inset?: boolean}) { return ( <MenuItemPrimitive data-slot="dropdown-menu-sub-trigger" data-inset={inset} textValue={typeof children === "string" ? children : props.textValue} className={cn( "flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-8 data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", className )} {...props} > {composeRenderProps(children, (children) => ( <> {children} <ChevronRightIcon className="ml-auto" /> </> ))} </MenuItemPrimitive> )}
function DropdownMenuSubContent({ placement = "end top", crossOffset = -3, offset = 0, className, ...props}: React.ComponentProps<typeof DropdownMenu>) { return ( <DropdownMenu data-slot="dropdown-menu-sub-content" className={cn("w-auto min-w-[96px] rounded-md bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10", className )} placement={placement} crossOffset={crossOffset} offset={offset} {...props} /> )}
function DropdownMenuSeparator({ className, ...props}: React.ComponentProps<typeof SeparatorPrimitive>) { return ( <SeparatorPrimitive data-slot="dropdown-menu-separator" className={cn("-mx-1 my-1 h-px bg-border", className)} {...props} /> )}
function DropdownMenuShortcut({ className, ...props}: React.ComponentProps<"span">) { return ( <span data-slot="dropdown-menu-shortcut" className={cn( "ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground", className )} {...props} /> )}
export { DropdownMenuTrigger, DropdownMenu, DropdownMenuGroup, DropdownMenuLabel, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubTrigger, DropdownMenuSubContent,}Usage
import { Button } from "@/components/ui/button"import { DropdownMenu, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger,} from "@/components/ui/dropdown-menu"<DropdownMenuTrigger> <Button variant="outline">Order actions</Button> <DropdownMenu> <DropdownMenuGroup> <DropdownMenuLabel>Order PO-2041</DropdownMenuLabel> <DropdownMenuItem onAction={() => duplicateOrder(order.id)}> Duplicate </DropdownMenuItem> </DropdownMenuGroup> <DropdownMenuSeparator /> <DropdownMenuItem variant="destructive">Cancel order</DropdownMenuItem> </DropdownMenu></DropdownMenuTrigger>Run an item's work in onAction, not onPress. Give every item that is selectable an id. The menu is as wide as its trigger, with a minimum of min-w-32, so set a width on DropdownMenu with className when the labels are longer than the button. This menu uses the React Aria API. Menubar uses Base UI, and their parts cannot be mixed.
Examples
Icons
Put an icon before the label to speed up scanning. When an item holds an icon and text, give it a textValue so that typing a letter finds it.
Submenu
DropdownMenuSub holds a DropdownMenuSubTrigger and a DropdownMenuSubContent. Use a submenu for a short list of choices that belong to one item, and do not go deeper than two levels.
Checkboxes
Set selectionMode="multiple" on a DropdownMenuGroup to make its items toggles, with selectedKeys and onSelectionChange to hold the state. A check mark shows the selected items, and the menu stays open on each press.
Radio
Set selectionMode="single" on the group for a choice of one. The selected item gets the check mark.
Destructive
variant="destructive" colours an item that removes data. Put it last, after a separator, and confirm with an Alert Dialog before you carry it out.
Icon trigger
A row of a table or a card often holds only an icon trigger. It needs an aria-label that names the row, and a menu that opens toward the page: bottom end for a trigger at the right.
Controlled
Pass isOpen and onOpenChange to DropdownMenuTrigger to read or set the open state. onAction on DropdownMenu receives the id of the chosen item.
Menu is closed. Last choice: Nothing yet.
Links
An item with an href renders a link and navigates through the router. Use it for items that go to another page.
Accessibility
| Key | Action |
|---|---|
| Space | Opens the menu from the trigger, with focus on the first item. |
| Enter | Opens the menu from the trigger, or chooses the focused item. |
| ↓ | Opens the menu from the trigger, or moves focus to the next item. |
| ↑ | Opens the menu from the trigger with focus on the last item, or moves focus to the previous item. |
| → | Opens the submenu of the focused item. |
| ← | Closes the submenu and returns focus to its item. |
| Esc | Closes the menu and returns focus to the trigger. |
| Any letter | Moves focus to the next item whose text starts with the typed letters. |
React Aria provides:
- The
menurole withmenuitem,menuitemcheckboxandmenuitemradioitems, and a trigger that reports whether the menu is open. - Arrow key navigation, type-ahead and submenus that open with a pointer or with the keys above.
- Focus that moves into the menu and returns to the trigger when it closes, and closing on an interaction outside.
- Disabled items that cannot be focused or chosen, and positioning that flips the menu when there is no room.
You provide:
- A visible name or an
aria-labelon the trigger. - Text on every item. For an item with an icon and text, add
textValue. - A
DropdownMenuLabelinside a group when the group needs a name. - A way to reach each action that does not depend on the menu, for the actions that matter most.
Guidelines
When to use
- For three to ten related actions on one object, such as an order or a supplier.
- For secondary actions in a row of a table, behind an icon trigger.
- For a setting with a few options that apply at once, with checkbox or radio items.
When not to use
- For the one main action of a view. Show it as a Button.
- For choosing a value in a form. Use a Select.
- For a menu that opens at the pointer on a right click. Use a Context Menu.
- For a persistent bar of menus across the top of an app. Use a Menubar.
- For fields, text or anything other than commands. Use a Popover.
- For navigation between sections of a site. Use a navigation menu.
Content
- Start with a verb and name the object when it is not clear: "Duplicate", "Cancel order".
- Write in sentence case, with no full stop. Keep each item to a few words.
- Order by how often people use the item, then by how risky it is. Put destructive items last.
- Group related items with a separator, and use a label only when a group needs a name.
Destructive items
Put the destructive item last, after a separator, so it is hard to hit by mistake.
Don’t put a destructive item first, with nothing between it and the safe ones.
API reference
DropdownMenuTrigger
Wraps the trigger and the menu through the React Aria MenuTrigger. It accepts every MenuTrigger prop.
| Prop | Type | Default | Description |
|---|---|---|---|
children | ReactNode | None | A pressable trigger, then the DropdownMenu. |
trigger? | "press" | "longPress" | "contextMenu" | "press" | How the menu opens. longPress keeps a press free for the trigger's own action. contextMenu opens it on a right click. |
isOpen? | boolean | None | Whether the menu is open. Makes the menu controlled. |
defaultOpen? | boolean | None | Whether the menu is open on first render, when uncontrolled. |
onOpenChange? | (isOpen: boolean) => void | None | Called when the menu opens or closes. |
DropdownMenu
Renders a React Aria Popover that holds a Menu. It accepts every Menu prop and the props below.
| Prop | Type | Default | Description |
|---|---|---|---|
placement? | Placement | "bottom start" | Where the menu opens relative to the trigger. |
offset? | number | 4 | The distance in pixels from the trigger along the main axis. |
crossOffset? | number | 0 | The shift in pixels along the cross axis. |
onAction? | (key: Key) => void | None | Called with the id of the item that was chosen. |
selectionMode? | "none" | "single" | "multiple" | None | Makes every item selectable. Set it on a group to limit it to that group. |
disabledKeys? | Iterable<Key> | None | The ids of the items that are disabled. |
autoFocus? | boolean | "first" | "last" | None | Where focus lands when the menu opens. |
className? | string | None | Classes merged onto the popover. Use it to set the width. |
children? | ReactNode | None | The groups, items, separators and submenus. |
DropdownMenuGroup
Renders a React Aria MenuSection. It accepts every MenuSection prop.
| Prop | Type | Default | Description |
|---|---|---|---|
selectionMode? | "none" | "single" | "multiple" | None | Makes the items of this group toggles or a radio choice. |
selectedKeys? | Selection | None | The ids of the selected items, when controlled. |
defaultSelectedKeys? | Selection | None | The ids of the items selected on first render. |
onSelectionChange? | (keys: Selection) => void | None | Called when the selection changes. |
DropdownMenuLabel
Renders a React Aria Header as a muted label for a group. Put it inside the group.
| Prop | Type | Default | Description |
|---|---|---|---|
inset? | boolean | None | Indents the label to line up with items that have a check mark or an icon. |
DropdownMenuItem
Renders a React Aria MenuItem. It accepts every MenuItem prop and the props below. In a selectable group it shows a check mark at the end.
| Prop | Type | Default | Description |
|---|---|---|---|
variant? | "default" | "destructive" | "default" | A destructive item is coloured as a warning. |
inset? | boolean | None | Indents the item to line up with items that have a check mark or an icon. |
id? | Key | None | The identity of the item, used by onAction and by selection. |
textValue? | string | None | The text used for type-ahead. Set automatically when the children are a string. |
onAction? | () => void | None | Called when the item is chosen. |
href? | string | None | Makes the item a link. |
isDisabled? | boolean | None | Stops the item from being focused or chosen. |
DropdownMenuSeparator
Renders a React Aria Separator, a thin line between groups.
DropdownMenuShortcut
A span that shows a shortcut at the end of an item. It displays the hint only: it does not register the key.
DropdownMenuSub
Wraps a DropdownMenuSubTrigger and a DropdownMenuSubContent through the React Aria SubmenuTrigger.
| Prop | Type | Default | Description |
|---|---|---|---|
delay? | number | 200 | Milliseconds before the submenu opens when the pointer rests on its trigger. |
DropdownMenuSubTrigger
A MenuItem that opens a submenu and shows a chevron. It accepts every MenuItem prop, and inset.
DropdownMenuSubContent
The popover of a submenu. It takes the props of DropdownMenu, with placement set to end top.