Menubar
A row of menus like the one at the top of a desktop app. One tab stop, full keyboard support.
NewInstallation
Copy and paste the following code into your project.
1'use client';23import { AnimatePresence, motion, useReducedMotion } from 'motion/react';4import * as React from 'react';5import { cn } from '../lib/cn';6import { getNavigationIndex, isTypeaheadKey, useTypeahead } from '../lib/collection';7import { type Direction, resolveDirection, useDirection } from '../lib/direction';8import { type FloatingAlign, FloatingPortal, useFloating } from '../lib/floating';9import { type FloatingSide, floatingVariants, reveal } from '../lib/motion';10import { assignRef, useLayer } from '../lib/overlay';11import { useControllableState } from '../lib/use-controllable-state';1213type IconProps = React.SVGProps<SVGSVGElement> & {14 size?: number | string;15};1617function CheckIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {18 return (19 <svg20 xmlns="http://www.w3.org/2000/svg"21 width={size}22 height={size}23 viewBox="0 0 24 24"24 fill="none"25 stroke="currentColor"26 strokeWidth={strokeWidth}27 strokeLinecap="round"28 strokeLinejoin="round"29 aria-hidden="true"30 {...props}31 >32 <path d="M20 6 9 17l-5-5" />33 </svg>34 );35}3637function DotIcon({ size = 24, ...props }: IconProps) {38 return (39 <svg40 xmlns="http://www.w3.org/2000/svg"41 width={size}42 height={size}43 viewBox="0 0 24 24"44 fill="currentColor"45 aria-hidden="true"46 {...props}47 >48 <circle cx="12" cy="12" r="4" />49 </svg>50 );51}5253function ChevronRightIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {54 return (55 <svg56 xmlns="http://www.w3.org/2000/svg"57 width={size}58 height={size}59 viewBox="0 0 24 24"60 fill="none"61 stroke="currentColor"62 strokeWidth={strokeWidth}63 strokeLinecap="round"64 strokeLinejoin="round"65 aria-hidden="true"66 {...props}67 >68 <path d="m9 18 6-6-6-6" />69 </svg>70 );71}7273type FocusTarget = 'first' | 'last' | 'none';7475type MenubarItemRole = 'menuitem' | 'menuitemcheckbox' | 'menuitemradio';7677interface MenubarContextValue {78 value: string;79 dir: Direction;80 tabStop: string;81 setTabStop: (value: string) => void;82 openMenu: (value: string, focus?: FocusTarget) => void;83 closeMenu: (options?: { restoreFocus?: boolean }) => void;84 moveMenu: (from: string, key: string, open: boolean) => boolean;85 focusTargetRef: React.RefObject<FocusTarget>;86 rootRef: React.RefObject<HTMLDivElement | null>;87}8889interface MenubarMenuContextValue {90 value: string;91 open: boolean;92 triggerRef: React.RefObject<HTMLButtonElement | null>;93 contentRef: React.RefObject<HTMLDivElement | null>;94 triggerId: string;95 contentId: string;96}9798interface MenubarLevelContextValue {99 open: boolean;100 activeSub: string | null;101 setActiveSub: React.Dispatch<React.SetStateAction<string | null>>;102}103104interface MenubarSubContextValue {105 open: boolean;106 openSub: (focus: FocusTarget) => void;107 closeSub: (options?: { restoreFocus?: boolean }) => void;108 focusTargetRef: React.RefObject<FocusTarget>;109 triggerRef: React.RefObject<HTMLDivElement | null>;110 contentRef: React.RefObject<HTMLDivElement | null>;111 triggerId: string;112 contentId: string;113}114115interface MenubarRadioGroupContextValue {116 value: string;117 setValue: (value: string) => void;118}119120interface MenubarProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'defaultValue' | 'dir'> {121 value?: string;122 defaultValue?: string;123 onValueChange?: (value: string) => void;124 dir?: Direction;125 loop?: boolean;126 ref?: React.Ref<HTMLDivElement>;127}128129interface MenubarMenuProps {130 children: React.ReactNode;131 value?: string;132}133134interface MenubarTriggerProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'type'> {135 children: React.ReactNode;136 ref?: React.Ref<HTMLButtonElement>;137}138139interface MenubarContentProps {140 children: React.ReactNode;141 className?: string;142 align?: 'start' | 'center' | 'end';143 sideOffset?: number;144}145146interface MenubarItemProps {147 children: React.ReactNode;148 onClick?: (event: React.MouseEvent<HTMLDivElement>) => void;149 onSelect?: () => void;150 className?: string;151 disabled?: boolean;152 variant?: 'default' | 'destructive';153 shortcut?: React.ReactNode;154 closeOnSelect?: boolean;155}156157interface MenubarCheckboxItemProps extends MenubarItemProps {158 checked?: boolean;159 defaultChecked?: boolean;160 onCheckedChange?: (checked: boolean) => void;161}162163interface MenubarRadioGroupProps extends Omit<164 React.HTMLAttributes<HTMLDivElement>,165 'defaultValue' | 'onChange'166> {167 children: React.ReactNode;168 value?: string;169 defaultValue?: string;170 onValueChange?: (value: string) => void;171}172173interface MenubarRadioItemProps extends MenubarItemProps {174 value: string;175}176177interface MenubarSubProps {178 children: React.ReactNode;179}180181interface MenubarSubTriggerProps {182 children: React.ReactNode;183 className?: string;184 disabled?: boolean;185}186187interface MenubarSubContentProps {188 children: React.ReactNode;189 className?: string;190 sideOffset?: number;191}192193interface MenubarGroupProps extends React.HTMLAttributes<HTMLDivElement> {194 children: React.ReactNode;195}196197interface MenubarSurfaceProps {198 children: React.ReactNode;199 className?: string;200 open: boolean;201 id: string;202 labelledBy: string;203 slot: string;204 dir: Direction;205 side: FloatingSide;206 align: FloatingAlign;207 sideOffset: number;208 alignOffset: number;209 anchorRef: React.RefObject<HTMLElement | null>;210 contentRef: React.RefObject<HTMLDivElement | null>;211 focusTargetRef: React.RefObject<FocusTarget>;212 outsideRef?: React.RefObject<HTMLElement | null>;213 onOutside?: () => void;214 onEscape: () => void;215 onTab: () => void;216 onHorizontal: (key: string, forward: boolean) => void;217}218219const MENUBAR_CONTENT_STYLE = { willChange: 'opacity, transform, filter' } as const;220221const ORIGIN_CLASSES: Record<FloatingSide, Record<FloatingAlign, string>> = {222 bottom: { start: 'origin-top-left', center: 'origin-top', end: 'origin-top-right' },223 top: { start: 'origin-bottom-left', center: 'origin-bottom', end: 'origin-bottom-right' },224 right: { start: 'origin-top-left', center: 'origin-left', end: 'origin-bottom-left' },225 left: { start: 'origin-top-right', center: 'origin-right', end: 'origin-bottom-right' },226};227228const ITEM_SELECTOR = ['menuitem', 'menuitemcheckbox', 'menuitemradio']229 .map((role) => `[role="${role}"]:not([aria-disabled="true"])`)230 .join(', ');231232const MenubarContext = React.createContext<MenubarContextValue | null>(null);233const MenubarMenuContext = React.createContext<MenubarMenuContextValue | null>(null);234const MenubarSurfaceContext = React.createContext(false);235const MenubarLevelContext = React.createContext<MenubarLevelContextValue | null>(null);236const MenubarSubContext = React.createContext<MenubarSubContextValue | null>(null);237const MenubarRadioGroupContext = React.createContext<MenubarRadioGroupContextValue | null>(null);238239const useMenubarContext = (): MenubarContextValue => {240 const context = React.use(MenubarContext);241 if (!context) throw new Error('Menubar components must be used within Menubar');242 return context;243};244245const useMenubarMenuContext = (): MenubarMenuContextValue => {246 const context = React.use(MenubarMenuContext);247 if (!context)248 throw new Error('Menubar.Trigger and Menubar.Content must be used within Menubar.Menu');249 return context;250};251252const useMenubarSubContext = (): MenubarSubContextValue => {253 const context = React.use(MenubarSubContext);254 if (!context)255 throw new Error('Menubar.SubTrigger and Menubar.SubContent must be used within Menubar.Sub');256 return context;257};258259function useClickOutside(260 ref: React.RefObject<HTMLElement | null>,261 triggerRef: React.RefObject<HTMLElement | null> | undefined,262 handler: (() => void) | undefined,263 enabled: boolean,264 isInsideUpperLayer: (target: EventTarget | null) => boolean,265) {266 React.useEffect(() => {267 if (!enabled || !handler) return;268 const handlePointerDownOutside = (event: PointerEvent) => {269 if (270 ref.current?.contains(event.target as Node) ||271 triggerRef?.current?.contains(event.target as Node) ||272 isInsideUpperLayer(event.target)273 ) {274 return;275 }276 handler();277 };278 document.addEventListener('pointerdown', handlePointerDownOutside);279 return () => document.removeEventListener('pointerdown', handlePointerDownOutside);280 }, [ref, triggerRef, handler, enabled, isInsideUpperLayer]);281}282283function getTriggers(root: HTMLElement | null): HTMLButtonElement[] {284 if (!root) return [];285 return Array.from(286 root.querySelectorAll<HTMLButtonElement>('[data-slot="menubar-trigger"]:not([disabled])'),287 );288}289290function getMenuItems(container: HTMLElement | null): HTMLElement[] {291 if (!container) return [];292 return Array.from(container.querySelectorAll<HTMLElement>(ITEM_SELECTOR));293}294295function focusEdge(container: HTMLElement | null, edge: FocusTarget) {296 if (edge === 'none') return;297 const items = getMenuItems(container);298 (edge === 'last' ? items[items.length - 1] : items[0])?.focus();299}300301const MenubarRoot = ({302 value: valueProp,303 defaultValue = '',304 onValueChange,305 dir: dirProp,306 loop = true,307 className,308 children,309 ref,310 ...props311}: MenubarProps): React.JSX.Element => {312 const [value, setValue] = useControllableState({313 value: valueProp,314 defaultValue,315 onChange: onValueChange,316 });317 const explicitDir = useDirection(dirProp);318 const rootRef = React.useRef<HTMLDivElement | null>(null);319 const focusTargetRef = React.useRef<FocusTarget>('first');320 const [tabStop, setTabStop] = React.useState('');321 const [dir, setDir] = React.useState<Direction>(explicitDir ?? 'ltr');322323 React.useLayoutEffect(() => {324 setDir(resolveDirection(rootRef.current, explicitDir));325 }, [explicitDir]);326327 React.useLayoutEffect(() => {328 const triggers = getTriggers(rootRef.current);329 if (triggers.some((trigger) => trigger.dataset.value === tabStop)) return;330 setTabStop(triggers[0]?.dataset.value ?? '');331 }, [children, tabStop]);332333 const setRootRef = React.useCallback(334 (node: HTMLDivElement | null) => {335 rootRef.current = node;336 assignRef(ref, node);337 },338 [ref],339 );340341 const openMenu = React.useCallback(342 (next: string, focus: FocusTarget = 'first') => {343 focusTargetRef.current = focus;344 setTabStop(next);345 setValue(next);346 },347 [setValue],348 );349350 const closeMenu = React.useCallback(351 (options?: { restoreFocus?: boolean }) => {352 const trigger = getTriggers(rootRef.current).find(353 (candidate) => candidate.dataset.value === value,354 );355 setValue('');356 if (options?.restoreFocus !== false) trigger?.focus();357 },358 [setValue, value],359 );360361 const moveMenu = React.useCallback(362 (from: string, key: string, open: boolean) => {363 const triggers = getTriggers(rootRef.current);364 const current = triggers.findIndex((trigger) => trigger.dataset.value === from);365 const index = getNavigationIndex(key, current, triggers.length, {366 orientation: 'horizontal',367 rtl: resolveDirection(rootRef.current, explicitDir) === 'rtl',368 loop,369 });370 if (index === null) return false;371 const target = triggers[index];372 if (!target) return false;373 const next = target.dataset.value ?? '';374 if (open) {375 if (next !== value) openMenu(next, 'first');376 } else {377 setTabStop(next);378 target.focus();379 }380 return true;381 },382 [explicitDir, loop, openMenu, value],383 );384385 const contextValue = React.useMemo(386 () => ({387 value,388 dir,389 tabStop,390 setTabStop,391 openMenu,392 closeMenu,393 moveMenu,394 focusTargetRef,395 rootRef,396 }),397 [value, dir, tabStop, openMenu, closeMenu, moveMenu],398 );399400 return (401 <MenubarContext value={contextValue}>402 <div403 ref={setRootRef}404 role="menubar"405 dir={dirProp}406 data-slot="menubar"407 className={cn('bg-card flex items-center gap-1 rounded-md p-1 shadow-sm', className)}408 {...props}409 >410 {children}411 </div>412 </MenubarContext>413 );414};415416const MenubarMenu = ({ children, value: valueProp }: MenubarMenuProps): React.JSX.Element => {417 const root = useMenubarContext();418 const id = React.useId();419 const value = valueProp ?? `menubar-menu-${id}`;420 const open = root.value !== '' && root.value === value;421 const triggerRef = React.useRef<HTMLButtonElement>(null);422 const contentRef = React.useRef<HTMLDivElement>(null);423 const triggerId = `menubar-trigger-${id}`;424 const contentId = `menubar-content-${id}`;425426 const contextValue = React.useMemo(427 () => ({ value, open, triggerRef, contentRef, triggerId, contentId }),428 [value, open, triggerId, contentId],429 );430431 return <MenubarMenuContext value={contextValue}>{children}</MenubarMenuContext>;432};433434const MenubarTrigger = ({435 children,436 className,437 disabled = false,438 onClick,439 onKeyDown,440 onPointerEnter,441 onFocus,442 ref,443 ...props444}: MenubarTriggerProps): React.JSX.Element => {445 const root = useMenubarContext();446 const menu = useMenubarMenuContext();447 const { triggerRef } = menu;448449 const setTriggerRef = React.useCallback(450 (node: HTMLButtonElement | null) => {451 triggerRef.current = node;452 assignRef(ref, node);453 },454 [triggerRef, ref],455 );456457 const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {458 onClick?.(e);459 if (e.defaultPrevented || disabled) return;460 if (!menu.open) {461 root.openMenu(menu.value, 'first');462 return;463 }464 if (e.detail === 0) focusEdge(menu.contentRef.current, 'first');465 else root.closeMenu();466 };467468 const handleKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>) => {469 onKeyDown?.(e);470 if (e.defaultPrevented || disabled) return;471 switch (e.key) {472 case 'ArrowDown':473 case 'ArrowUp': {474 e.preventDefault();475 const edge = e.key === 'ArrowUp' ? 'last' : 'first';476 if (menu.open) focusEdge(menu.contentRef.current, edge);477 else root.openMenu(menu.value, edge);478 return;479 }480 case 'ArrowLeft':481 case 'ArrowRight':482 case 'Home':483 case 'End':484 if (root.moveMenu(menu.value, e.key, root.value !== '')) e.preventDefault();485 return;486 case 'Escape':487 if (!menu.open) return;488 e.preventDefault();489 root.closeMenu();490 return;491 case 'Tab':492 if (root.value !== '') root.closeMenu({ restoreFocus: false });493 return;494 }495 };496497 const handlePointerEnter = (e: React.PointerEvent<HTMLButtonElement>) => {498 onPointerEnter?.(e);499 if (disabled || e.pointerType === 'touch') return;500 if (root.value === '' || menu.open) return;501 root.openMenu(menu.value, 'none');502 e.currentTarget.focus();503 };504505 const handleFocus = (e: React.FocusEvent<HTMLButtonElement>) => {506 onFocus?.(e);507 root.setTabStop(menu.value);508 };509510 return (511 <button512 ref={setTriggerRef}513 type="button"514 role="menuitem"515 id={menu.triggerId}516 aria-haspopup="menu"517 aria-expanded={menu.open}518 aria-controls={menu.open ? menu.contentId : undefined}519 tabIndex={root.tabStop === '' || root.tabStop === menu.value ? 0 : -1}520 disabled={disabled}521 data-slot="menubar-trigger"522 data-value={menu.value}523 data-state={menu.open ? 'open' : 'closed'}524 data-disabled={disabled || undefined}525 className={cn(526 'text-foreground flex items-center rounded-sm px-3 py-1.5 text-sm font-medium outline-none select-none',527 'hover:bg-muted data-[state=open]:bg-muted transition-colors duration-150',528 'ring-offset-background focus-visible:ring-ring focus-visible:ring-2 focus-visible:ring-offset-2',529 'disabled:pointer-events-none disabled:opacity-40',530 className,531 )}532 {...props}533 onClick={handleClick}534 onKeyDown={handleKeyDown}535 onPointerEnter={handlePointerEnter}536 onFocus={handleFocus}537 >538 {children}539 </button>540 );541};542543const MenubarLevel = ({ children }: { children: React.ReactNode }) => {544 const open = React.use(MenubarSurfaceContext);545 const [activeSub, setActiveSub] = React.useState<string | null>(null);546547 const contextValue = React.useMemo(() => ({ open, activeSub, setActiveSub }), [open, activeSub]);548549 return <MenubarLevelContext value={contextValue}>{children}</MenubarLevelContext>;550};551552const MenubarSurface = ({553 children,554 className,555 open,556 id,557 labelledBy,558 slot,559 dir,560 side,561 align,562 sideOffset,563 alignOffset,564 anchorRef,565 contentRef,566 focusTargetRef,567 outsideRef,568 onOutside,569 onEscape,570 onTab,571 onHorizontal,572}: MenubarSurfaceProps): React.JSX.Element => {573 const layer = useLayer(open, false, contentRef);574 const typeahead = useTypeahead();575 const shouldReduceMotion = useReducedMotion();576 const { style: floatingStyle, side: resolvedSide } = useFloating({577 open,578 anchorRef,579 floatingRef: contentRef,580 side,581 align,582 sideOffset,583 alignOffset,584 });585586 useClickOutside(contentRef, outsideRef, onOutside, open, layer.isInsideUpperLayer);587588 React.useEffect(() => {589 if (!open) return;590 const frame = requestAnimationFrame(() => {591 focusEdge(contentRef.current, focusTargetRef.current);592 });593 return () => cancelAnimationFrame(frame);594 }, [open, contentRef, focusTargetRef]);595596 const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {597 const container = contentRef.current;598 if (!container || !container.contains(e.target as Node)) return;599600 if (e.key === 'Escape') {601 e.preventDefault();602 onEscape();603 return;604 }605 if (e.key === 'Tab') {606 onTab();607 return;608 }609 if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {610 const forward = e.key === (dir === 'rtl' ? 'ArrowLeft' : 'ArrowRight');611 const active = document.activeElement;612 if (613 forward &&614 active instanceof HTMLElement &&615 active.dataset.slot === 'menubar-sub-trigger' &&616 container.contains(active)617 ) {618 return;619 }620 e.preventDefault();621 onHorizontal(e.key, forward);622 return;623 }624625 const items = getMenuItems(container);626 if (items.length === 0) return;627628 const currentIndex = items.indexOf(document.activeElement as HTMLElement);629630 let nextIndex: number | null = null;631 if (e.key === 'ArrowDown') {632 nextIndex = currentIndex < 0 ? 0 : (currentIndex + 1) % items.length;633 } else if (e.key === 'ArrowUp') {634 nextIndex =635 currentIndex < 0 ? items.length - 1 : (currentIndex - 1 + items.length) % items.length;636 } else if (e.key === 'Home') {637 nextIndex = 0;638 } else if (e.key === 'End') {639 nextIndex = items.length - 1;640 } else if (isTypeaheadKey(e, typeahead.isTyping())) {641 e.preventDefault();642 e.stopPropagation();643 typeahead.search(e.key, items, currentIndex)?.focus();644 return;645 }646647 if (nextIndex !== null) {648 e.preventDefault();649 items[nextIndex]?.focus();650 }651 };652653 const style = React.useMemo(654 () => ({655 ...floatingStyle,656 ...(open ? null : { visibility: undefined }),657 ...MENUBAR_CONTENT_STYLE,658 }),659 [floatingStyle, open],660 );661662 return (663 <MenubarSurfaceContext value={open}>664 <FloatingPortal>665 <AnimatePresence>666 {open && (667 <motion.div668 ref={contentRef}669 id={id}670 role="menu"671 tabIndex={-1}672 dir={dir}673 aria-labelledby={labelledBy}674 data-slot={slot}675 data-state="open"676 data-side={resolvedSide}677 onKeyDownCapture={handleKeyDown}678 variants={shouldReduceMotion ? reveal : floatingVariants[resolvedSide]}679 initial="hidden"680 animate="visible"681 exit="exit"682 style={style}683 className={cn(684 'bg-popover text-popover-foreground z-500 max-h-(--available-height) min-w-48 overflow-y-auto overscroll-contain rounded-md shadow-md outline-none',685 ORIGIN_CLASSES[resolvedSide][align],686 className,687 )}688 >689 <MenubarLevel>690 <div className="flex flex-col gap-0.5 p-1">{children}</div>691 </MenubarLevel>692 </motion.div>693 )}694 </AnimatePresence>695 </FloatingPortal>696 </MenubarSurfaceContext>697 );698};699700const MenubarContent = ({701 children,702 className,703 align = 'start',704 sideOffset = 6,705}: MenubarContentProps): React.JSX.Element => {706 const root = useMenubarContext();707 const menu = useMenubarMenuContext();708 const rtl = root.dir === 'rtl';709 const physicalAlign: FloatingAlign =710 align === 'center' ? 'center' : (align === 'start') === !rtl ? 'start' : 'end';711712 const { closeMenu } = root;713 const dismiss = React.useCallback(() => closeMenu({ restoreFocus: false }), [closeMenu]);714715 return (716 <MenubarSurface717 open={menu.open}718 id={menu.contentId}719 labelledBy={menu.triggerId}720 slot="menubar-content"721 dir={root.dir}722 side="bottom"723 align={physicalAlign}724 sideOffset={sideOffset}725 alignOffset={0}726 anchorRef={menu.triggerRef}727 contentRef={menu.contentRef}728 focusTargetRef={root.focusTargetRef}729 outsideRef={root.rootRef}730 onOutside={dismiss}731 onEscape={() => root.closeMenu()}732 onTab={() => root.closeMenu()}733 onHorizontal={(key) => root.moveMenu(menu.value, key, true)}734 className={className}735 >736 {children}737 </MenubarSurface>738 );739};740741const itemClassName = (disabled: boolean, variant: 'default' | 'destructive') =>742 cn(743 'relative flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none select-none',744 'transition-colors duration-150',745 'focus:bg-muted pointer-coarse:py-2.5',746 disabled && 'pointer-events-none opacity-40',747 variant === 'destructive' && 'text-destructive-text focus:text-destructive-text',748 );749750const MenubarShortcut = ({751 children,752 className,753}: {754 children: React.ReactNode;755 className?: string;756}) => (757 <span758 data-slot="menubar-shortcut"759 className={cn('text-muted-foreground ms-auto ps-6 text-xs tracking-widest', className)}760 >761 {children}762 </span>763);764765interface MenubarItemBaseProps extends MenubarItemProps {766 role: MenubarItemRole;767 slot: string;768 checked?: boolean;769 indicator?: React.ReactNode;770}771772const MenubarItemBase = ({773 children,774 onClick,775 onSelect,776 className,777 disabled = false,778 variant = 'default',779 shortcut,780 role,781 slot,782 checked,783 indicator,784 closeOnSelect = role === 'menuitem',785}: MenubarItemBaseProps): React.JSX.Element => {786 const { closeMenu } = useMenubarContext();787 const level = React.use(MenubarLevelContext);788 const checkable = role !== 'menuitem';789790 const select = (e: React.MouseEvent<HTMLDivElement>) => {791 onClick?.(e);792 onSelect?.();793 if (closeOnSelect) closeMenu();794 };795796 const handleClick = (e: React.MouseEvent<HTMLDivElement>) => {797 if (disabled) return;798 e.stopPropagation();799 select(e);800 };801802 const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {803 if (disabled) return;804 if (e.key !== 'Enter' && e.key !== ' ') return;805 e.preventDefault();806 e.stopPropagation();807 select(e as unknown as React.MouseEvent<HTMLDivElement>);808 };809810 const handlePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {811 if (disabled || e.pointerType === 'touch') return;812 level?.setActiveSub(null);813 if (document.activeElement !== e.currentTarget) e.currentTarget.focus();814 };815816 const handlePointerLeave = (e: React.PointerEvent<HTMLDivElement>) => {817 if (document.activeElement !== e.currentTarget) return;818 e.currentTarget.closest<HTMLElement>('[role="menu"]')?.focus();819 };820821 return (822 <div823 role={role}824 tabIndex={-1}825 aria-disabled={disabled || undefined}826 aria-checked={checkable ? Boolean(checked) : undefined}827 data-slot={slot}828 data-state={checkable ? (checked ? 'checked' : 'unchecked') : undefined}829 data-disabled={disabled || undefined}830 data-variant={variant}831 onClick={handleClick}832 onKeyDown={handleKeyDown}833 onPointerMove={handlePointerMove}834 onPointerLeave={handlePointerLeave}835 className={cn(itemClassName(disabled, variant), checkable && 'ps-8', className)}836 >837 {indicator}838 {children}839 {shortcut !== undefined && shortcut !== null && <MenubarShortcut>{shortcut}</MenubarShortcut>}840 </div>841 );842};843844const MenubarItem = (props: MenubarItemProps): React.JSX.Element => (845 <MenubarItemBase {...props} role="menuitem" slot="menubar-item" />846);847848const MenubarCheckboxItem = ({849 checked: checkedProp,850 defaultChecked = false,851 onCheckedChange,852 onSelect,853 ...props854}: MenubarCheckboxItemProps): React.JSX.Element => {855 const [checked, setChecked] = useControllableState({856 value: checkedProp,857 defaultValue: defaultChecked,858 onChange: onCheckedChange,859 });860861 return (862 <MenubarItemBase863 {...props}864 role="menuitemcheckbox"865 slot="menubar-checkbox-item"866 checked={checked}867 onSelect={() => {868 setChecked(!checked);869 onSelect?.();870 }}871 indicator={872 <span className="absolute start-2 flex size-4 items-center justify-center">873 {checked && <CheckIcon size={14} />}874 </span>875 }876 />877 );878};879880const MenubarRadioGroup = ({881 children,882 value: valueProp,883 defaultValue = '',884 onValueChange,885 className,886 ...props887}: MenubarRadioGroupProps): React.JSX.Element => {888 const [value, setValue] = useControllableState({889 value: valueProp,890 defaultValue,891 onChange: onValueChange,892 });893894 const contextValue = React.useMemo(() => ({ value, setValue }), [value, setValue]);895896 return (897 <MenubarRadioGroupContext value={contextValue}>898 <div899 role="group"900 data-slot="menubar-radio-group"901 className={cn('flex flex-col gap-0.5', className)}902 {...props}903 >904 {children}905 </div>906 </MenubarRadioGroupContext>907 );908};909910const MenubarRadioItem = ({911 value,912 onSelect,913 closeOnSelect = true,914 ...props915}: MenubarRadioItemProps): React.JSX.Element => {916 const group = React.use(MenubarRadioGroupContext);917 if (!group) throw new Error('Menubar.RadioItem must be used within Menubar.RadioGroup');918 const checked = group.value === value;919920 return (921 <MenubarItemBase922 {...props}923 role="menuitemradio"924 slot="menubar-radio-item"925 checked={checked}926 closeOnSelect={closeOnSelect}927 onSelect={() => {928 if (!checked) group.setValue(value);929 onSelect?.();930 }}931 indicator={932 <span className="absolute start-2 flex size-4 items-center justify-center">933 {checked && <DotIcon size={14} />}934 </span>935 }936 />937 );938};939940const MenubarSub = ({ children }: MenubarSubProps): React.JSX.Element => {941 const level = React.use(MenubarLevelContext);942 if (!level) throw new Error('Menubar.Sub must be used within Menubar.Content');943 const id = React.useId();944 const open = level.open && level.activeSub === id;945 const triggerRef = React.useRef<HTMLDivElement>(null);946 const contentRef = React.useRef<HTMLDivElement>(null);947 const focusTargetRef = React.useRef<FocusTarget>('none');948 const { setActiveSub } = level;949950 const openSub = React.useCallback(951 (focus: FocusTarget) => {952 focusTargetRef.current = focus;953 if (open) focusEdge(contentRef.current, focus);954 else setActiveSub(id);955 },956 [open, setActiveSub, id],957 );958959 const closeSub = React.useCallback(960 (options?: { restoreFocus?: boolean }) => {961 setActiveSub((current) => (current === id ? null : current));962 if (options?.restoreFocus !== false) triggerRef.current?.focus();963 },964 [setActiveSub, id],965 );966967 const contextValue = React.useMemo(968 () => ({969 open,970 openSub,971 closeSub,972 focusTargetRef,973 triggerRef,974 contentRef,975 triggerId: `menubar-sub-trigger-${id}`,976 contentId: `menubar-sub-content-${id}`,977 }),978 [open, openSub, closeSub, id],979 );980981 return <MenubarSubContext value={contextValue}>{children}</MenubarSubContext>;982};983984const MenubarSubTrigger = ({985 children,986 className,987 disabled = false,988}: MenubarSubTriggerProps): React.JSX.Element => {989 const root = useMenubarContext();990 const { open, openSub, triggerRef, triggerId, contentId } = useMenubarSubContext();991 const forwardKey = root.dir === 'rtl' ? 'ArrowLeft' : 'ArrowRight';992993 const handleClick = (e: React.MouseEvent<HTMLDivElement>) => {994 if (disabled) return;995 e.stopPropagation();996 openSub(e.detail === 0 ? 'first' : 'none');997 };998999 const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {1000 if (disabled) return;1001 if (e.key !== 'Enter' && e.key !== ' ' && e.key !== forwardKey) return;1002 e.preventDefault();1003 e.stopPropagation();1004 openSub('first');1005 };10061007 const handlePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {1008 if (disabled || e.pointerType === 'touch') return;1009 if (document.activeElement !== e.currentTarget) e.currentTarget.focus();1010 if (!open) openSub('none');1011 };10121013 const handlePointerLeave = (e: React.PointerEvent<HTMLDivElement>) => {1014 if (document.activeElement !== e.currentTarget) return;1015 e.currentTarget.closest<HTMLElement>('[role="menu"]')?.focus();1016 };10171018 return (1019 <div1020 ref={triggerRef}1021 id={triggerId}1022 role="menuitem"1023 tabIndex={-1}1024 aria-haspopup="menu"1025 aria-expanded={open}1026 aria-controls={open ? contentId : undefined}1027 aria-disabled={disabled || undefined}1028 data-slot="menubar-sub-trigger"1029 data-state={open ? 'open' : 'closed'}1030 data-disabled={disabled || undefined}1031 onClick={handleClick}1032 onKeyDown={handleKeyDown}1033 onPointerMove={handlePointerMove}1034 onPointerLeave={handlePointerLeave}1035 className={cn(itemClassName(disabled, 'default'), 'data-[state=open]:bg-muted', className)}1036 >1037 {children}1038 <ChevronRightIcon1039 size={14}1040 className="text-muted-foreground ms-auto size-3.5 rtl:rotate-180"1041 />1042 </div>1043 );1044};10451046const MenubarSubContent = ({1047 children,1048 className,1049 sideOffset = 6,1050}: MenubarSubContentProps): React.JSX.Element => {1051 const root = useMenubarContext();1052 const menu = useMenubarMenuContext();1053 const sub = useMenubarSubContext();10541055 return (1056 <MenubarSurface1057 open={sub.open}1058 id={sub.contentId}1059 labelledBy={sub.triggerId}1060 slot="menubar-sub-content"1061 dir={root.dir}1062 side={root.dir === 'rtl' ? 'left' : 'right'}1063 align="start"1064 sideOffset={sideOffset}1065 alignOffset={-5}1066 anchorRef={sub.triggerRef}1067 contentRef={sub.contentRef}1068 focusTargetRef={sub.focusTargetRef}1069 onEscape={() => sub.closeSub()}1070 onTab={() => root.closeMenu()}1071 onHorizontal={(key, forward) => {1072 if (forward) root.moveMenu(menu.value, key, true);1073 else sub.closeSub();1074 }}1075 className={className}1076 >1077 {children}1078 </MenubarSurface>1079 );1080};10811082const MenubarGroup = ({ children, className, ...props }: MenubarGroupProps): React.JSX.Element => (1083 <div1084 role="group"1085 data-slot="menubar-group"1086 className={cn('flex flex-col gap-0.5', className)}1087 {...props}1088 >1089 {children}1090 </div>1091);10921093const MenubarLabel = ({1094 children,1095 className,1096}: {1097 children: React.ReactNode;1098 className?: string;1099}): React.JSX.Element => (1100 <div1101 role="presentation"1102 data-slot="menubar-label"1103 className={cn('text-muted-foreground px-2 py-2 text-xs font-medium', className)}1104 >1105 {children}1106 </div>1107);11081109const MenubarSeparator = ({ className }: { className?: string }): React.JSX.Element => (1110 <div1111 role="separator"1112 aria-orientation="horizontal"1113 data-slot="menubar-separator"1114 className={cn('bg-border/50 my-1 h-px', className)}1115 />1116);11171118const Menubar = Object.assign(MenubarRoot, {1119 Menu: MenubarMenu,1120 Trigger: MenubarTrigger,1121 Content: MenubarContent,1122 Item: MenubarItem,1123 CheckboxItem: MenubarCheckboxItem,1124 RadioGroup: MenubarRadioGroup,1125 RadioItem: MenubarRadioItem,1126 Sub: MenubarSub,1127 SubTrigger: MenubarSubTrigger,1128 SubContent: MenubarSubContent,1129 Group: MenubarGroup,1130 Label: MenubarLabel,1131 Separator: MenubarSeparator,1132 Shortcut: MenubarShortcut,1133});11341135export { Menubar };1136export type {1137 MenubarCheckboxItemProps,1138 MenubarContentProps,1139 MenubarGroupProps,1140 MenubarItemProps,1141 MenubarMenuProps,1142 MenubarProps,1143 MenubarRadioGroupProps,1144 MenubarRadioItemProps,1145 MenubarSubContentProps,1146 MenubarSubProps,1147 MenubarSubTriggerProps,1148 MenubarTriggerProps,1149};
Update the import paths to match your project structure.
Anatomy
1import { Menubar } from '@/components/menubar';
1<Menubar aria-label="Editor">2 <Menubar.Menu>3 <Menubar.Trigger>File</Menubar.Trigger>4 <Menubar.Content>5 <Menubar.Item shortcut="⌘N">New file</Menubar.Item>6 <Menubar.Separator />7 <Menubar.Sub>8 <Menubar.SubTrigger>Share</Menubar.SubTrigger>9 <Menubar.SubContent>10 <Menubar.Item>Copy link</Menubar.Item>11 </Menubar.SubContent>12 </Menubar.Sub>13 </Menubar.Content>14 </Menubar.Menu>15</Menubar>
Composition
Use the following composition to build a
Menubar:Menubar└── Menubar.Menu├── Menubar.Trigger└── Menubar.Content├── Menubar.Label├── Menubar.Item├── Menubar.Group├── Menubar.CheckboxItem├── Menubar.RadioGroup│ └── Menubar.RadioItem├── Menubar.Sub│ ├── Menubar.SubTrigger│ └── Menubar.SubContent└── Menubar.Separator
The menus look and behave like
DropdownMenu: same surface, same items, same animation. Once a menu is open, moving the pointer over another trigger opens that one without a click, the way desktop menu bars work.Variants
Default
A text editor menu bar with shortcuts, a Find submenu, a checkbox to show the ruler and a radio group for the zoom level.
Controlled
Pass
value and onValueChange to know which menu is open. Give each Menubar.Menu a value so you can refer to it. An empty string means every menu is closed.1const [open, setOpen] = React.useState('');23<Menubar value={open} onValueChange={setOpen} aria-label="Editor">4 <Menubar.Menu value="file">...</Menubar.Menu>5 <Menubar.Menu value="edit">...</Menubar.Menu>6</Menubar>;
Keyboard
| Key | Action |
|---|---|
ArrowLeft, ArrowRight | Move between triggers. With a menu open, open the neighbor menu instead |
Home, End | Jump to the first or last trigger |
ArrowDown, Enter, Space | Open the menu and focus its first item |
ArrowUp | Open the menu and focus its last item |
ArrowUp, ArrowDown | Move between items inside an open menu |
ArrowRight | On a submenu trigger, open the submenu |
ArrowLeft | Inside a submenu, close it and go back to its trigger |
| Typing | Focus the next item whose label starts with it |
Enter, Space | Run the focused item, or toggle it when it is a checkbox |
Escape | Close the menu and return focus to its trigger |
Tab | Close every menu and move on to the next element on the page |
In right-to-left layouts,
ArrowLeft and ArrowRight swap.Accessibility
- The bar has
role="menubar"and each trigger is amenuitemwitharia-haspopup="menu"andaria-expanded. Name the bar witharia-label. - Only one trigger is in the tab order at a time, so
Tabenters and leaves the bar in one step. - Each open menu has
role="menu"and is labelled by its trigger. Checkbox and radio items usemenuitemcheckboxandmenuitemradiowitharia-checked. - Shortcuts are plain text. The menubar does not listen for them, so wire them up yourself if the app needs them.
- The direction comes from
dir, from aDirectionProvideror from the closestdirattribute, and submenus open towards the end of the line.
API Reference
Menubar
Accepts every
div attribute.| Prop | Type | Default | Description |
|---|---|---|---|
value | string | - | Controlled open menu. An empty string closes them all |
defaultValue | string | '' | Menu open on first render when uncontrolled |
onValueChange | (value: string) => void | - | Called when a menu opens or every menu closes |
dir | 'ltr' | 'rtl' | - | Reading direction for arrow keys and submenus |
loop | boolean | true | Wrap around from the last trigger to the first |
className | string | - | Additional CSS classes |
Menubar.Menu
| Prop | Type | Default | Description |
|---|---|---|---|
value | string | generated id | Identifies the menu in value and onValueChange |
Menubar.Trigger
Accepts every
button attribute.| Prop | Type | Default | Description |
|---|---|---|---|
disabled | boolean | false | Skips the trigger in keyboard navigation |
className | string | - | Additional CSS classes |
Menubar.Content
| Prop | Type | Default | Description |
|---|---|---|---|
align | 'start' | 'center' | 'end' | 'start' | Alignment against the trigger |
sideOffset | number | 6 | Gap between the trigger and the menu |
className | string | - | Additional CSS classes |
Menubar.Item
| Prop | Type | Default | Description |
|---|---|---|---|
shortcut | ReactNode | - | Hint shown at the end of the item |
onSelect | () => void | - | Called when the item is picked |
disabled | boolean | false | Skips the item and blocks selection |
variant | 'default' | 'destructive' | 'default' | Visual style |
closeOnSelect | boolean | true | Close the menu after picking the item |
className | string | - | Additional CSS classes |
Menubar.CheckboxItem
Keeps the menu open after a toggle, so people can switch several options in one go.
| Prop | Type | Default | Description |
|---|---|---|---|
checked | boolean | - | Controlled checked state |
defaultChecked | boolean | false | Initial state when uncontrolled |
onCheckedChange | (checked: boolean) => void | - | Called with the new value |
shortcut | ReactNode | - | Hint shown at the end of the item |
closeOnSelect | boolean | false | Close the menu after toggling |
disabled | boolean | false | Disable the item |
Menubar.RadioGroup
Accepts every
div attribute, so give it an aria-label when it has no visible label.| Prop | Type | Default | Description |
|---|---|---|---|
value | string | - | Controlled selected value |
defaultValue | string | '' | Initial value when uncontrolled |
onValueChange | (value: string) => void | - | Called when another option is picked |
Menubar.RadioItem
| Prop | Type | Default | Description |
|---|---|---|---|
value | string | - | Value reported to the group |
shortcut | ReactNode | - | Hint shown at the end of the item |
closeOnSelect | boolean | true | Close the menu after picking |
disabled | boolean | false | Disable the item |
Menubar.Sub, Menubar.SubTrigger, Menubar.SubContent
Menubar.Sub wraps a nested menu. It opens on hover, on click and with ArrowRight, and only one submenu per level stays open.| Prop | Type | Default | Description |
|---|---|---|---|
disabled | boolean | false | SubTrigger only. Skips it and keeps the submenu closed |
sideOffset | number | 6 | SubContent only. Gap between the submenu and its trigger |
className | string | - | Additional CSS classes |
Menubar.Group, Menubar.Label, Menubar.Separator, Menubar.Shortcut
Menubar.Shortcut is the same hint the shortcut prop renders, for items with custom content.| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Additional CSS classes |
Found something to improve?
Notice a bug, typo, or missing detail on this page? Help us make the documentation better by opening a GitHub issue.