Skip to main content

DropdownMenu

Accessible dropdown menu component for creating interactive command menus with keyboard navigation, typeahead search, and full ARIA support.

Live Demo​

This example wraps the items in a DropdownMenu.Viewport with a bounded height, so the list scrolls within the menu. Keyboard navigation and typeahead keep the highlighted item in view. It also demonstrates item highlighting, selection affordances, and the optional arrow.

Features​

  • ✅ Typeahead search for quick item selection
  • ✅ Controlled and uncontrolled state management
  • ✅ Automatic positioning with collision detection
  • ✅ Modal and non-modal modes
  • ✅ Customizable close behavior per item type
  • ✅ Automatic portal rendering to document.body
  • ✅ Polymorphic component API

Import​

import { DropdownMenu } from '@turkish-technology/spar';

Anatomy​

The DropdownMenu component is built as a compound component with multiple parts:

Parts
RootContainer managing state and context
TriggerButton that toggles menu visibility
ContentMenu container with positioning
ViewportScrollable region wrapping the menu items
ItemIndividual selectable menu option
GroupSemantic grouping container for related items
LabelNon-interactive label for a menu group
SeparatorVisual divider between menu sections
ArrowOptional decorative arrow element

Structure​

<DropdownMenu.Root>
<DropdownMenu.Trigger />
<DropdownMenu.Content>
<DropdownMenu.Viewport>
<DropdownMenu.Label />
<DropdownMenu.Item />
<DropdownMenu.Group>
<DropdownMenu.Item />
</DropdownMenu.Group>
<DropdownMenu.Separator />
</DropdownMenu.Viewport>
<DropdownMenu.Arrow />
</DropdownMenu.Content>
</DropdownMenu.Root>

DropdownMenu.Viewport is optional — omit it for short menus. Wrap the items in a viewport when the list can grow long enough to need a bounded, scrollable area.

Alternative: Tree-shakeable named imports

import {
DropdownMenuRoot,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
} from '@turkish-technology/spar';

<DropdownMenuRoot>
<DropdownMenuTrigger />
<DropdownMenuContent>
<DropdownMenuItem />
</DropdownMenuContent>
</DropdownMenuRoot>;

Data Flow:

  • DropdownMenu.Root manages open/close state and provides context
  • DropdownMenu.Trigger controls menu visibility and manages focus
  • DropdownMenu.Content handles positioning, keyboard navigation, and item collection
  • Menu items register themselves for keyboard navigation and typeahead

Code Examples​

Basic Dropdown Menu​

A simple dropdown menu with standard items.

function BasicMenu() {
return (
<DropdownMenu.Root>
<DropdownMenu.Trigger>Actions</DropdownMenu.Trigger>
<DropdownMenu.Content>
<DropdownMenu.Item onSelect={() => console.log('Edit')}>
Edit
</DropdownMenu.Item>
<DropdownMenu.Item onSelect={() => console.log('Duplicate')}>
Duplicate
</DropdownMenu.Item>
<DropdownMenu.Separator />
<DropdownMenu.Item onSelect={() => console.log('Delete')}>
Delete
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
);
}

Controlled Menu State​

Control the menu's open state externally.

function ControlledMenu() {
const [isOpen, setIsOpen] = React.useState(false);

return (
<>
<p>Menu is {isOpen ? 'open' : 'closed'}</p>
<DropdownMenu.Root open={isOpen} onOpenChange={setIsOpen}>
<DropdownMenu.Trigger>Options</DropdownMenu.Trigger>
<DropdownMenu.Content>
<DropdownMenu.Item>Option 1</DropdownMenu.Item>
<DropdownMenu.Item>Option 2</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
</>
);
}

Custom Positioning​

Control menu positioning.

function CustomPositionMenu() {
return (
<DropdownMenu.Root>
<DropdownMenu.Trigger>Options</DropdownMenu.Trigger>
<DropdownMenu.Content side="right" align="start">
<DropdownMenu.Item>Option 1</DropdownMenu.Item>
<DropdownMenu.Item>Option 2</DropdownMenu.Item>
<DropdownMenu.Item>Option 3</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
);
}

Grouped Menu Items​

Group related items together.

function GroupedMenu() {
return (
<DropdownMenu.Root>
<DropdownMenu.Trigger>Edit</DropdownMenu.Trigger>
<DropdownMenu.Content>
<DropdownMenu.Group>
<DropdownMenu.Label>Clipboard</DropdownMenu.Label>
<DropdownMenu.Item>Cut</DropdownMenu.Item>
<DropdownMenu.Item>Copy</DropdownMenu.Item>
<DropdownMenu.Item>Paste</DropdownMenu.Item>
</DropdownMenu.Group>
<DropdownMenu.Separator />
<DropdownMenu.Group>
<DropdownMenu.Label>Transform</DropdownMenu.Label>
<DropdownMenu.Item>Uppercase</DropdownMenu.Item>
<DropdownMenu.Item>Lowercase</DropdownMenu.Item>
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
);
}

Scrollable Menu​

Wrap the items in DropdownMenu.Viewport to keep a long list within a bounded, scrollable area. The Viewport is headless — set a max-height and overflow via CSS to enable scrolling. Keyboard navigation and typeahead automatically keep the highlighted item in view.

function ScrollableMenu() {
return (
<DropdownMenu.Root>
<DropdownMenu.Trigger>Timezone</DropdownMenu.Trigger>
<DropdownMenu.Content>
<DropdownMenu.Viewport style={{ maxHeight: 240, overflowY: 'auto' }}>
{timezones.map(tz => (
<DropdownMenu.Item key={tz}>{tz}</DropdownMenu.Item>
))}
</DropdownMenu.Viewport>
</DropdownMenu.Content>
</DropdownMenu.Root>
);
}

Disabled Items​

Disable specific menu items.

function MenuWithDisabledItems() {
const hasSelection = false;

return (
<DropdownMenu.Root>
<DropdownMenu.Trigger>Edit</DropdownMenu.Trigger>
<DropdownMenu.Content>
<DropdownMenu.Item disabled={!hasSelection}>Cut</DropdownMenu.Item>
<DropdownMenu.Item disabled={!hasSelection}>Copy</DropdownMenu.Item>
<DropdownMenu.Item>Paste</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
);
}

Non-Modal Menu​

Allow focus to leave the menu without closing.

function NonModalMenu() {
return (
<DropdownMenu.Root modal={false}>
<DropdownMenu.Trigger>Settings</DropdownMenu.Trigger>
<DropdownMenu.Content>
<DropdownMenu.Item>Preferences</DropdownMenu.Item>
<DropdownMenu.Item>Extensions</DropdownMenu.Item>
<DropdownMenu.Item>Keyboard Shortcuts</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
);
}

Add a decorative arrow pointing to the trigger.

function MenuWithArrow() {
return (
<DropdownMenu.Root>
<DropdownMenu.Trigger>Options</DropdownMenu.Trigger>
<DropdownMenu.Content>
<DropdownMenu.Item>Edit</DropdownMenu.Item>
<DropdownMenu.Item>Duplicate</DropdownMenu.Item>
<DropdownMenu.Separator />
<DropdownMenu.Item>Delete</DropdownMenu.Item>
<DropdownMenu.Arrow />
</DropdownMenu.Content>
</DropdownMenu.Root>
);
}

Custom Close Behavior​

Control when the menu closes on selection.

function CustomCloseBehavior() {
return (
<DropdownMenu.Root closeOnSelect={false}>
<DropdownMenu.Trigger>Multi-Select</DropdownMenu.Trigger>
<DropdownMenu.Content>
<DropdownMenu.Item>Option 1</DropdownMenu.Item>
<DropdownMenu.Item>Option 2</DropdownMenu.Item>
<DropdownMenu.Separator />
<DropdownMenu.Item onSelect={e => e.preventDefault()}>
Keep Open
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
);
}

API Reference​

The root container that manages the dropdown menu state and provides context to all child components. DropdownMenu and DropdownMenu.Root are the same component - the difference is only import/notation style.

Props

NameTypeDefaultDescription
id?stringundefinedCustom base ID for ARIA relationships. Auto-generated if not provided. Sub-element IDs are derived as ${id}-trigger and ${id}-content.
open?booleanundefinedControlled open state
defaultOpen?booleanfalseInitial open state (uncontrolled)
onOpenChange?(open: boolean) => voidundefinedCallback when open state changes
modal?booleantrueWhether menu traps focus (modal) or allows focus to leave
disabled?booleanfalseDisables all dropdown menu triggers (prevents opening)
dir?'ltr' | 'rtl''ltr'Reading direction for menu positioning
closeOnSelect?booleantrueWhether to close menu on item selection
children?React.ReactNodeundefinedMenu trigger and content

Events

NameParametersDescriptionWhen Triggered
onOpenChange(open: boolean)Open state change handlerUser interaction or programmatic state change

The button element that toggles the dropdown menu visibility. Extends all Button component props including polymorphic rendering via the as prop.

Props

NameTypeDefaultDescription
as?React.ElementType"button"Element type to render as
childrenReact.ReactNode | ((state: DropdownMenuTriggerRenderProps) => React.ReactNode)undefinedTrigger content or render props function
disabled?booleanfalseWhether the trigger is disabled
autoFocus?booleanfalseWhether the button should receive focus on mount
isLoading?booleanfalseLoading state with screen reader support
isPressed?booleanundefinedToggle state - creates a toggle button when defined
onPressedChange?(pressed: boolean) => voidundefinedCallback fired when toggle state changes
ref?React.Ref<HTMLButtonElement | null>undefinedForwarded ref to trigger element
onClick?(event: React.MouseEvent) => voidundefinedClick event handler
onKeyDown?(event: React.KeyboardEvent) => voidundefinedKeyboard event handler
...propsButtonProps-All standard Button component attributes

Render Props (DropdownMenuTriggerRenderProps)

PropertyTypeDescription
isOpenbooleanWhether the dropdown menu is open
disabledbooleanWhether the trigger is disabled
open() => voidFunction to open the dropdown menu
close() => voidFunction to close the dropdown menu
toggle() => voidFunction to toggle the dropdown menu

Events

NameParametersDescriptionWhen Triggered
onClick(event: React.MouseEvent)Mouse click handlerUser clicks trigger
onKeyDown(event: React.KeyboardEvent)Keyboard event handlerUser presses key while focused

HTML Attributes

AttributeValuePurpose
data-state'open' | 'closed'Current state for styling
data-disabled''Present when disabled

The container for menu items with positioning, keyboard navigation, and typeahead support.

Props

NameTypeDefaultDescription
as?React.ElementType'div'Polymorphic element type to render
side?'top' | 'right' | 'bottom' | 'left''bottom'Preferred side for positioning
align?'start' | 'center' | 'end''center'Alignment relative to trigger
container?HTMLElement | nulldocument.bodyCustom portal container element
onEscapeKeyDown?(event: KeyboardEvent) => voidundefinedEscape key handler; event.preventDefault() prevents close
onPointerDownOutside?(event: PointerEvent) => voidundefinedOutside click handler; event.preventDefault() prevents close
onFocusOutside?(event: FocusEvent) => voidundefinedOutside focus handler (cancelable event); event.preventDefault() prevents close (non-modal) or focus recapture (modal)
onKeyDown?(event: React.KeyboardEvent) => voidundefinedKeyboard event handler
ref?React.Ref<HTMLElement | null>undefinedForwarded ref to content element
children?React.ReactNodeundefinedMenu items and groups

Events

NameParametersDescriptionWhen Triggered
onEscapeKeyDown(event: KeyboardEvent)Escape key pressedUser presses Escape while menu is open
onPointerDownOutside(event: PointerEvent)Click outside menuUser clicks outside menu bounds
onFocusOutside(event: FocusEvent)Focus leaves menuFocus moves outside menu (modal and non-modal)
onKeyDown(event: React.KeyboardEvent)Key pressed in menuUser presses any key while menu is focused

HTML Attributes

AttributeValuePurpose
data-state'open'Indicates open state
data-sideSideCurrent placement side
data-alignAlignCurrent alignment
tabIndex-1Manages focus programmatically

An optional scrollable region that wraps the menu items. Use it when the list can grow long enough to need a bounded, scrollable area. Headless: renders a plain element with no visual opinions — apply a max-height and overflow (e.g. overflow-y: auto) via className/style to enable scrolling.

Because menu items are focused programmatically (with preventScroll), the browser will not reveal off-screen items on its own. DropdownMenu.Viewport is purely presentational — it just provides the bounded, scrollable box. Keeping the highlighted item visible during keyboard navigation and typeahead is handled by DropdownMenu.Content, which scrolls the item into its nearest scrollable ancestor (this Viewport). It works the same whether or not a Viewport is present.

Defaults to role="presentation" so it stays transparent in the accessibility tree, preserving the menu → menuitem structure. Override role if you need different semantics.

Props

NameTypeDefaultDescription
as?React.ElementType'div'Polymorphic element type to render
role?string'presentation'ARIA role for the viewport element
ref?React.Ref<HTMLElement | null>undefinedForwarded ref to the viewport element
children?React.ReactNodeundefinedMenu items, groups, labels, and separators
...propsHTMLAttributes-All standard element attributes (className, style, etc.)

Events

NameParametersDescriptionWhen Triggered
N/AN/ANo interactive eventsViewport is a non-interactive wrapper

HTML Attributes

AttributeValuePurpose
role'presentation'Keeps the viewport transparent in the a11y tree

A selectable menu item.

Props

NameTypeDefaultDescription
as?React.ElementType'div'Polymorphic element type to render
role?string'menuitem'ARIA role for the item element
disabled?booleanfalseWhether item is disabled
onSelect?(event: React.SyntheticEvent) => voidundefinedSelection handler
textValue?stringundefinedText value for typeahead (auto-detected from content if not provided)
ref?React.Ref<HTMLElement | null>undefinedForwarded ref to item element
children?React.ReactNodeundefinedItem content

Events

NameParametersDescriptionWhen Triggered
onSelect(event: React.SyntheticEvent)Item selectedUser clicks or activates item with keyboard
onClick(event: React.MouseEvent)Mouse clickUser clicks item
onKeyDown(event: React.KeyboardEvent)Key pressedUser presses key while item focused
onPointerMove(event: React.PointerEvent)Pointer movementPointer moves over item
onPointerLeave(event: React.PointerEvent)Pointer leaves itemPointer moves away from item
onFocus(event: React.FocusEvent)Item receives focusItem gains focus

HTML Attributes

AttributeValuePurpose
tabIndex0 | -1Controls keyboard focus (0 when highlighted, -1 otherwise)
aria-disabledtruePresent when disabled; conveys disabled state to assistive technology
data-disabled''Present when disabled
data-highlighted''Present when highlighted

A visual separator between menu sections.

Props

NameTypeDefaultDescription
as?React.ElementType'div'Polymorphic element type to render
ref?React.Ref<HTMLElement | null>undefinedForwarded ref to separator element

Events

NameParametersDescriptionWhen Triggered
N/AN/ANo interactive eventsSeparator is non-interactive

HTML Attributes

AttributeValuePurpose
data-orientation'horizontal'Indicates orientation

A non-interactive label for menu sections.

Props

NameTypeDefaultDescription
as?React.ElementType'div'Polymorphic element type to render
ref?React.Ref<HTMLElement | null>undefinedForwarded ref to label element
children?React.ReactNodeundefinedLabel content

Events

NameParametersDescriptionWhen Triggered
N/AN/ANo interactive eventsLabel is non-interactive

A logical grouping container for related menu items.

Props

NameTypeDefaultDescription
as?React.ElementType'div'Polymorphic element type to render
ref?React.Ref<HTMLElement | null>undefinedForwarded ref to group element
children?React.ReactNodeundefinedMenu items or labels

Events

NameParametersDescriptionWhen Triggered
N/AN/ANo interactive eventsGroup is non-interactive container

HTML Attributes

AttributeValuePurpose
role'group'Semantic grouping role for assistive technology

Optional decorative arrow element that points to the trigger. Headless: renders a plain element with no visual opinions — user provides all styling. Arrow ref is automatically managed via context.

Supports polymorphic rendering via the as prop. When rendered as the default svg, sensible SVG defaults (width, height, viewBox, and a triangle polygon) are applied automatically. When rendered as another element (e.g., as="div"), SVG-specific attributes and default children are omitted.

Props

NameTypeDefaultDescription
as?React.ElementType'svg'Polymorphic element type to render
ref?React.Ref<Element>undefinedForward ref support
children?React.ReactNodeundefinedCustom arrow content. When as="svg" (default), falls back to a triangle polygon
className?stringundefinedCSS class names for styling
style?React.CSSPropertiesundefinedCustom styles for arrow

Events

NameParametersDescriptionWhen Triggered
None-Arrow is purely decorative-

HTML Attributes

AttributeValuePurpose
aria-hidden"true"Hidden from assistive technology
data-placement"top" | "bottom" | "left" | "right" (with optional align)Indicates arrow placement

Keyboard Interactions​

Complete keyboard behavior for the DropdownMenu component:

KeyActionContextNotes
SpaceOpens menu / Activates itemTrigger / Menu itemOpens menu from trigger, activates focused item
EnterOpens menu / Activates itemTrigger / Menu itemOpens menu from trigger, activates focused item
ArrowDownOpens menu focusing first / Next itemTrigger / MenuFrom trigger opens and focuses first item, in menu moves to next item
ArrowUpOpens menu focusing last / Previous itemTrigger / MenuFrom trigger opens and focuses last item, in menu moves to previous item
EscapeCloses menuMenuRestores focus to trigger; onEscapeKeyDown(event.preventDefault()) prevents close
TabNavigate / CloseMenuIn modal mode, moves through items; in non-modal mode, closes menu
Shift + TabNavigate backwardMenu (modal)Moves to previous item in modal mode
HomeFirst itemMenuMoves focus to first item
EndLast itemMenuMoves focus to last item
Character keysTypeahead searchMenuFocuses first item matching typed characters