---
title: "Menubar · Ark UI — StyleX Blocks"
description: "A horizontal bar of application menus with arrow-key navigation between them, checkable items, and radio groups."
url: "https://stylexblocks.com/components/ark-ui/menubar/"
agent:
  instructions: "Use this search API to find relevant components and blocks across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://stylexblocks.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# Menubar

A horizontal bar of application menus with arrow-key navigation between them, checkable items, and radio groups.

- Behavior engine: Ark UI
- Also available for: [Base UI](https://stylexblocks.com/components/base-ui/menubar.md), [UI SDK](https://stylexblocks.com/components/ui-sdk/menubar.md)
- Category: Display
- Variants: subtle, solid
- Sizes: sm, md
- HTML page: https://stylexblocks.com/components/ark-ui/menubar/

## Install

Configure the project once (sets the behavior engine and import aliases):

```sh
npx stylexblocks init
```

Then add the item as source you own:

```sh
npx stylexblocks add menubar
```

Equivalent: `npx shadcn add @stylexblocks/menubar`. Registry item JSON: https://stylexblocks.com/r/ark-ui/menubar.json

## Usage

```tsx
import { Menubar } from "#components/ui/ark-ui/menubar.tsx";

export function Example() {
  return (
    // A WAI-ARIA menubar of Ark menus: ←/→ move along the bar and carry an
    // open menu over to its neighbour; hovering switches while one is open.
    // size/variant resolve once on Root; every dropdown inherits them.
    <Menubar.Root size="md">
      <Menubar.Menu value="file">
        <Menubar.Trigger>File</Menubar.Trigger>
        <Menubar.Portal>
          <Menubar.Positioner>
            <Menubar.Content>
              <Menubar.Item value="new-tab">
                <Menubar.ItemText>New tab</Menubar.ItemText>
                <Menubar.ItemCommand>⌘T</Menubar.ItemCommand>
              </Menubar.Item>
            </Menubar.Content>
          </Menubar.Positioner>
        </Menubar.Portal>
      </Menubar.Menu>
      <Menubar.Menu value="edit">
        <Menubar.Trigger>Edit</Menubar.Trigger>
        <Menubar.Portal>
          <Menubar.Positioner>
            <Menubar.Content>
              <Menubar.Item value="undo">
                <Menubar.ItemText>Undo</Menubar.ItemText>
                <Menubar.ItemCommand>⌘Z</Menubar.ItemCommand>
              </Menubar.Item>
            </Menubar.Content>
          </Menubar.Positioner>
        </Menubar.Portal>
      </Menubar.Menu>
    </Menubar.Root>
  );
}
```

## Source

`components/ui/ark-ui/menubar.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import { createContext, useContext, useId, useMemo, useRef, useState } from "react";
import { Menu as ArkMenu } from "@ark-ui/react/menu";
import { Portal } from "@ark-ui/react/portal";
import { mergeProps } from "@ark-ui/react/utils";
import { createSlotRecipeContext } from "#lib/ark-ui/create-slot-recipe-context.tsx";
import {
  defineSlotRecipe,
  resolveSlotStyles,
  type StyleOverrideProps,
} from "#lib/recipe-props.ts";
import { fontWeights } from "@stylexblocks/ui/tokens/font-weights.stylex.ts";
import { semanticShadows } from "@stylexblocks/ui/semantic-tokens/shadows.stylex.ts";
import { cursor } from '@stylexblocks/ui/tokens/cursor.stylex.ts'
import { durations } from '@stylexblocks/ui/tokens/durations.stylex.ts'
import { fontSizes } from '@stylexblocks/ui/tokens/font-sizes.stylex.ts'
import { letterSpacings } from '@stylexblocks/ui/tokens/letter-spacings.stylex.ts'
import { lineHeights } from '@stylexblocks/ui/tokens/line-heights.stylex.ts'
import { semanticColors } from '@stylexblocks/ui/semantic-tokens/colors.stylex.ts'
import { semanticRadii } from '@stylexblocks/ui/semantic-tokens/radii.stylex.ts'
import { sizes } from '@stylexblocks/ui/tokens/sizes.stylex.ts'
import { spacing } from '@stylexblocks/ui/tokens/spacing.stylex.ts'
import { zIndices } from '@stylexblocks/ui/tokens/z-indices.stylex.ts'

const menuContent = stylex.create({
  base: {
    outline: 'none',
    color: semanticColors.fg,
    maxHeight: 'var(--available-height)',
    '--menu-z-index': zIndices.layer3,
    zIndex: 'calc(var(--menu-z-index) + var(--layer-index, 0))',
    overflowY: 'auto',
    scrollbarWidth: 'thin',
    transformOrigin: 'var(--transform-origin)',
    animationName: {
      default: null,
      ':is([data-open], [data-state="open"])': 'fade-in, slide-from-top',
      ':is([data-closed], [data-state="closed"])': 'fade-out',
    },
    animationDuration: {
      default: null,
      ':is([data-open], [data-state="open"])': durations.fast,
      ':is([data-closed], [data-state="closed"])': durations.faster,
    },
  },
})

const menuContentSizes = stylex.create({
  sm: {
    minWidth: '8rem',
    padding: spacing._1,
    borderRadius: semanticRadii.panel,
  },
  md: {
    minWidth: '8rem',
    padding: spacing._1,
  },
})

const menuItem = stylex.create({
  base: {
    textDecoration: 'none',
    color: semanticColors.fg,
    userSelect: 'none',
    borderRadius: semanticRadii.control,
    width: '100%',
    display: 'flex',
    cursor: {
      default: cursor.menuitem,
      ':is(:disabled, [disabled], [data-disabled])': 'not-allowed',
    },
    alignItems: 'center',
    textAlign: 'start',
    position: 'relative',
    flex: '0 0 auto',
    outline: 'none',
    opacity: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 0.5,
    },
  },
})

const menuItemSizes = stylex.create({
  sm: {
    gap: spacing._1,
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
    minHeight: sizes._6,
    paddingInline: spacing._1_5,
    paddingInlineStart: `var(--menu-item-inset, ${spacing._1_5})`,
  },
  md: {
    gap: spacing._2,
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
    minHeight: sizes._7,
    paddingInline: spacing._2,
    paddingInlineStart: `var(--menu-item-inset, ${spacing._2})`,
  },
})

const menuItemVariants = stylex.create({
  subtle: {},
  solid: {},
})

const menuItemText = stylex.create({
  base: {
    flex: 1,
  },
})

const menuItemGroupLabel = stylex.create({
  base: {
    display: 'flex',
    alignItems: 'center',
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
    color: semanticColors.fgSubtle,
  },
})

const menuItemGroupLabelSizes = stylex.create({
  sm: {
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
    minHeight: sizes._6,
    paddingInline: spacing._1_5,
  },
  md: {
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
    minHeight: sizes._7,
    paddingInline: spacing._2,
  },
})

const menuIndicator = stylex.create({
  base: {
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    flexShrink: 0,
  },
})

const menuItemCommand = stylex.create({
  base: {
    opacity: 0.6,
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
    marginInlineStart: 'auto',
    paddingInlineStart: spacing._4,
    letterSpacing: letterSpacings.widest,
  },
})

const menuSeparator = stylex.create({
  base: {
    height: '1px',
    backgroundColor: semanticColors.bgMuted,
    marginBlock: spacing._1,
    marginInline: spacing._1,
  },
})

export type MenuVariant = keyof typeof menuItemVariants

export type MenuSize = keyof typeof menuContentSizes

// defineSlotRecipe validates the shape at compile time: default values must
// exist in the axis maps, and slot keys must be `styles` or a declared axis
const menuRecipe = defineSlotRecipe({
  slots: {
    content: { styles: menuContent, sizes: menuContentSizes },
    item: { styles: menuItem, sizes: menuItemSizes, variants: menuItemVariants },
    itemText: { styles: menuItemText },
    itemGroupLabel: {
      styles: menuItemGroupLabel,
      sizes: menuItemGroupLabelSizes,
    },
    indicator: { styles: menuIndicator },
    itemCommand: { styles: menuItemCommand },
    separator: { styles: menuSeparator },
  },
  defaultVariants: { size: "md", variant: "subtle" },
});

// The dropdowns are the menu recipe unchanged (plus Menu's local chrome);
// only the bar and its triggers are new. Triggers highlight like menu items
// (bgSubtle) on hover, keyboard focus, and while their menu is open.
const chrome = stylex.create({
  bar: {
    display: "inline-flex",
    alignItems: "center",
    gap: spacing._0_5,
    backgroundColor: semanticColors.bgPanel,
    borderWidth: "1px",
    borderStyle: "solid",
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    boxShadow: semanticShadows.xs,
  },
  trigger: {
    display: "inline-flex",
    alignItems: "center",
    whiteSpace: "nowrap",
    userSelect: "none",
    borderWidth: 0,
    borderRadius: semanticRadii.control,
    color: semanticColors.fg,
    fontWeight: fontWeights.medium,
    outline: "none",
    cursor: {
      default: cursor.button,
      ":is(:disabled, [data-disabled])": "not-allowed",
    },
    opacity: {
      default: null,
      ":is(:disabled, [data-disabled])": 0.5,
    },
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.bgSubtle,
      ":focus-visible": semanticColors.bgSubtle,
      ':is([data-state="open"], [data-popup-open], [data-highlighted])':
        semanticColors.bgSubtle,
    },
  },
  content: {
    "--menu-z-index": zIndices.dropdown,
    backgroundColor: semanticColors.bgPanel,
    borderRadius: semanticRadii.panel,
    boxShadow: semanticShadows.overlay,
  },
  item: {
    paddingBlock: spacing._1,
    backgroundColor: {
      default: null,
      ":is([data-highlighted])": semanticColors.bgSubtle,
    },
  },
  itemCommand: {
    marginInlineStart: "auto",
    paddingInlineStart: spacing._4,
  },
  indicator: {
    width: "1rem",
    height: "1rem",
    display: "inline-flex",
    visibility: {
      default: "visible",
      ":is([hidden])": "hidden",
    },
  },
});

const barSizes = stylex.create({
  sm: { padding: spacing._0_5 },
  md: { padding: spacing._1 },
});

const triggerSizes = stylex.create({
  sm: {
    height: sizes._6,
    paddingInline: spacing._1_5,
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
  },
  md: {
    height: sizes._7,
    paddingInline: spacing._2,
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
  },
});

function CheckIcon(props: React.ComponentProps<"svg">) {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true" {...props}>
      <path d="m3.5 8.5 3 3 6-7" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

const { withProvider, withContext } = createSlotRecipeContext(menuRecipe);

// ---------------------------------------------------------------------------
// Menubar coordination. Ark has no menubar primitive, so the bar is hand-built
// on the WAI-ARIA menubar pattern: one `role="menubar"` with a roving tab
// stop over its `role="menuitem"` triggers, each hosting a real Ark menu. The
// bar owns which menu is open (each Ark menu is controlled), so:
//   - ←/→ on a trigger moves focus along the bar (wrapping), Home/End jump;
//   - ←/→ inside an open menu closes it and opens the neighbour with its
//     first item highlighted;
//   - while any menu is open, hovering another trigger switches to it.
// ---------------------------------------------------------------------------

interface MenubarContextValue {
  id: string;
  openValue: string | null;
  activeValue: string | null;
  setOpen: (value: string, open: boolean) => void;
  setActive: (value: string) => void;
  /** Move along the bar; `open` carries an open menu over to the target. */
  move: (from: string, to: 1 | -1 | "first" | "last", open: boolean) => void;
  /** Open `value` straight away (hover switching). */
  switchTo: (value: string, trigger: HTMLElement) => void;
  /** Where a closing menu returns focus while the bar is switching menus. */
  switchTarget: React.RefObject<HTMLElement | null>;
}

const MenubarContext = createContext<MenubarContextValue | null>(null);
const MenuValueContext = createContext<string | null>(null);

function useMenubar(part: string) {
  const ctx = useContext(MenubarContext);
  if (!ctx) throw new Error(`Menubar.${part} must be used within Menubar.Root`);
  return ctx;
}

function getTriggers(id: string) {
  return Array.from(
    document.querySelectorAll<HTMLElement>(`[data-menubar-trigger="${id}"]`),
  ).filter((el) => !el.hasAttribute("disabled") && !el.hasAttribute("data-disabled"));
}

const StyledBar = withProvider(
  "div",
  (v) => [chrome.bar, barSizes[v.size]],
  "MenubarRoot",
);

function Root(props: React.ComponentProps<typeof StyledBar>) {
  const id = useId();
  const [openValue, setOpenValue] = useState<string | null>(null);
  const [activeValue, setActiveValue] = useState<string | null>(null);
  const switchTarget = useRef<HTMLElement | null>(null);

  const ctx = useMemo<MenubarContextValue>(() => {
    const releaseSwitch = () =>
      requestAnimationFrame(() =>
        requestAnimationFrame(() => {
          switchTarget.current = null;
        }),
      );
    return {
      id,
      openValue,
      activeValue,
      switchTarget,
      setOpen(value, open) {
        setOpenValue((current) => (open ? value : current === value ? null : current));
        if (open) setActiveValue(value);
      },
      setActive: setActiveValue,
      move(from, to, open) {
        const triggers = getTriggers(id);
        if (!triggers.length) return;
        const index = triggers.findIndex((el) => el.dataset.menubarValue === from);
        const nextIndex =
          to === "first"
            ? 0
            : to === "last"
              ? triggers.length - 1
              : (index + to + triggers.length) % triggers.length;
        const next = triggers[nextIndex]!;
        const nextValue = next.dataset.menubarValue!;
        setActiveValue(nextValue);
        if (!open) {
          next.focus();
          return;
        }
        // Hand the open state over to the neighbour. The closing menu returns
        // focus to the neighbour's trigger instead of its own (so the new
        // menu never sees a focus-outside); once the new content is mounted,
        // Home highlights its first item, as a keyboard-opened menu should.
        // Runs on the next task, outside the current keydown dispatch.
        switchTarget.current = next;
        setTimeout(() => {
          next.focus({ preventScroll: true });
          setOpenValue(nextValue);
          requestAnimationFrame(() =>
            requestAnimationFrame(() => {
              const content = document.getElementById(next.getAttribute("aria-controls") ?? "");
              if (content) {
                content.focus({ preventScroll: true });
                content.dispatchEvent(
                  new KeyboardEvent("keydown", { key: "Home", bubbles: true, cancelable: true }),
                );
              }
              switchTarget.current = null;
            }),
          );
        });
      },
      switchTo(value, trigger) {
        switchTarget.current = trigger;
        setOpenValue(value);
        setActiveValue(value);
        releaseSwitch();
      },
    };
  }, [id, openValue, activeValue]);

  return (
    <MenubarContext.Provider value={ctx}>
      <StyledBar role="menubar" aria-orientation="horizontal" {...props} />
    </MenubarContext.Provider>
  );
}
Root.displayName = "MenubarRoot";

/** One menu on the bar: a controlled Ark `Menu.Root` keyed by `value`. */
function MenubarMenu(
  props: Omit<ArkMenu.RootProps, "open" | "defaultOpen"> & { value: string },
) {
  const { value, onOpenChange, positioning, ...rest } = props;
  const bar = useMenubar("Menu");
  return (
    <MenuValueContext.Provider value={value}>
      <ArkMenu.Root
        {...rest}
        open={bar.openValue === value}
        onOpenChange={(details) => {
          bar.setOpen(value, details.open);
          onOpenChange?.(details);
        }}
        positioning={{ placement: "bottom-start", gutter: 6, ...positioning }}
        finalFocusEl={() => bar.switchTarget.current}
      />
    </MenuValueContext.Provider>
  );
}
MenubarMenu.displayName = "MenubarMenu";

const StyledTrigger = withContext(
  ArkMenu.Trigger,
  (v) => [chrome.trigger, triggerSizes[v.size]],
  "MenubarTrigger",
);

function Trigger(props: React.ComponentProps<typeof StyledTrigger>) {
  const bar = useMenubar("Trigger");
  const value = useContext(MenuValueContext);
  if (value == null) throw new Error("Menubar.Trigger must be used within Menubar.Menu");
  const tabbable = bar.activeValue == null || bar.activeValue === value;
  const own: React.ComponentProps<typeof StyledTrigger> = {
    role: "menuitem",
    tabIndex: tabbable ? 0 : -1,
    onKeyDown(event) {
      const open = bar.openValue != null;
      const keys: Record<string, 1 | -1 | "first" | "last"> = {
        ArrowRight: 1,
        ArrowLeft: -1,
        Home: "first",
        End: "last",
      };
      const to = keys[event.key];
      if (to == null) return;
      event.preventDefault();
      bar.move(value, to, open && (to === 1 || to === -1));
    },
    onPointerEnter(event) {
      if (event.pointerType !== "mouse") return;
      if (bar.openValue != null && bar.openValue !== value) {
        bar.switchTo(value, event.currentTarget);
      }
    },
    onFocus(event) {
      const switching = bar.switchTarget.current;
      if (switching && switching !== event.currentTarget) return;
      bar.setActive(value);
    },
  };
  return (
    <StyledTrigger
      data-menubar-trigger={bar.id}
      data-menubar-value={value}
      {...mergeProps(props, own)}
    />
  );
}
Trigger.displayName = "MenubarTrigger";

const StyledContent = withContext(
  ArkMenu.Content,
  (v) => [...resolveSlotStyles(menuRecipe.slots.content, v), chrome.content],
  "MenubarContent",
);

function Content(props: React.ComponentProps<typeof StyledContent>) {
  const bar = useMenubar("Content");
  const value = useContext(MenuValueContext);
  return (
    <StyledContent
      {...props}
      onKeyDownCapture={(event: React.KeyboardEvent<HTMLDivElement>) => {
        props.onKeyDownCapture?.(event);
        if (value == null) return;
        if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
        // → on a submenu trigger item belongs to the menu machine
        const highlighted = event.currentTarget.querySelector("[data-highlighted]");
        if (event.key === "ArrowRight" && highlighted?.getAttribute("data-part") === "trigger-item") {
          return;
        }
        event.preventDefault();
        event.stopPropagation();
        bar.move(value, event.key === "ArrowRight" ? 1 : -1, true);
      }}
    />
  );
}
Content.displayName = "MenubarContent";

const StyledItemIndicator = withContext(
  ArkMenu.ItemIndicator,
  (v) => [...resolveSlotStyles(menuRecipe.slots.indicator, v), chrome.indicator],
  "MenubarItemIndicator",
);

function ItemIndicator(
  allProps: Omit<React.ComponentProps<typeof ArkMenu.ItemIndicator>, "style"> & StyleOverrideProps,
) {
  const { children, ...rest } = allProps;
  return (
    <StyledItemIndicator {...rest}>{children ?? <CheckIcon />}</StyledItemIndicator>
  );
}
ItemIndicator.displayName = "MenubarItemIndicator";

/**
 * Menubar — a hand-built WAI-ARIA menubar (Ark has no menubar primitive)
 * hosting real Ark menus: each `Menubar.Menu` is Ark's menu machine (portal,
 * positioning, typeahead, item navigation) wearing the menu slot recipe,
 * while the bar coordinates which one is open, the roving tab stop, and
 * ←/→ between menus. `<Menubar.Root size variant>` resolves the recipe once;
 * every part, including the portaled dropdowns, inherits it through context.
 */
export const Menubar = {
  Root,
  Menu: MenubarMenu,
  Trigger,
  Portal,
  Positioner: ArkMenu.Positioner,
  Content,
  Item: withContext(
    ArkMenu.Item,
    (v) => [...resolveSlotStyles(menuRecipe.slots.item, v), chrome.item],
    "MenubarItem",
  ),
  ItemText: withContext(ArkMenu.ItemText, "itemText", "MenubarItemText"),
  ItemGroup: ArkMenu.ItemGroup,
  ItemGroupLabel: withContext(ArkMenu.ItemGroupLabel, "itemGroupLabel", "MenubarItemGroupLabel"),
  CheckboxItem: withContext(
    ArkMenu.CheckboxItem,
    (v) => [...resolveSlotStyles(menuRecipe.slots.item, v), chrome.item],
    "MenubarCheckboxItem",
  ),
  RadioItemGroup: ArkMenu.RadioItemGroup,
  RadioItem: withContext(
    ArkMenu.RadioItem,
    (v) => [...resolveSlotStyles(menuRecipe.slots.item, v), chrome.item],
    "MenubarRadioItem",
  ),
  ItemIndicator,
  ItemCommand: withContext(
    "span",
    (v) => [...resolveSlotStyles(menuRecipe.slots.itemCommand, v), chrome.itemCommand],
    "MenubarItemCommand",
  ),
  Separator: withContext(ArkMenu.Separator, "separator", "MenubarSeparator"),
};
```
