---
title: "Context Menu · Base UI — StyleX Blocks"
description: "A menu that opens at the pointer on right-click or long-press, with items, shortcuts, checkable items, and separators."
url: "https://stylexblocks.com/components/base-ui/context-menu/"
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/"
---

# Context Menu

A menu that opens at the pointer on right-click or long-press, with items, shortcuts, checkable items, and separators.

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

## Install

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

```sh
npx stylexblocks init --style base-ui
```

Then add the item as source you own:

```sh
npx stylexblocks add context-menu
```

Equivalent: `npx shadcn add @stylexblocks/context-menu`. Registry item JSON: https://stylexblocks.com/r/base-ui/context-menu.json

## Usage

```tsx
import { ContextMenu } from "#components/ui/base-ui/context-menu.tsx";

export function Example() {
  return (
    // Right-click (or long-press) the trigger area to open the menu at the
    // pointer. size/variant resolve once on Root; parts inherit them.
    <ContextMenu.Root size="md">
      <ContextMenu.Trigger>Right-click here</ContextMenu.Trigger>
      <ContextMenu.Portal>
        <ContextMenu.Positioner>
          <ContextMenu.Popup>
            <ContextMenu.Item>
              <ContextMenu.ItemText>Reload</ContextMenu.ItemText>
              <ContextMenu.ItemCommand>⌘R</ContextMenu.ItemCommand>
            </ContextMenu.Item>
            <ContextMenu.Separator />
            <ContextMenu.CheckboxItem defaultChecked>
              <ContextMenu.CheckboxItemIndicator />
              <ContextMenu.ItemText>Show bookmarks</ContextMenu.ItemText>
            </ContextMenu.CheckboxItem>
          </ContextMenu.Popup>
        </ContextMenu.Positioner>
      </ContextMenu.Portal>
    </ContextMenu.Root>
  );
}
```

## Source

`components/ui/base-ui/context-menu.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import { ContextMenu as BaseContextMenu } from "@base-ui/react/context-menu";
import { createSlotRecipeContext } from "#lib/base-ui/create-slot-recipe-context.tsx";
import {
  defineSlotRecipe,
  resolveSlotStyles,
  type StyleOverrideProps,
} from "#lib/recipe-props.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" },
});

// Local chrome the recipe leaves to the composition layer: the dropdown
// surface, keyboard/pointer highlight, and logical-property fixes for
// generated Chakra shorthands (`ms`/`ps`).
const chrome = stylex.create({
  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], [data-unchecked])": "hidden",
    },
  },
});

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 { withRootProvider, withContext } = createSlotRecipeContext(menuRecipe);

const StyledRadioItemIndicator = withContext(
  BaseContextMenu.RadioItemIndicator,
  (v) => [...resolveSlotStyles(menuRecipe.slots.indicator, v), chrome.indicator],
  "ContextMenuRadioItemIndicator",
);

function RadioItemIndicator(
  allProps: Omit<React.ComponentProps<typeof BaseContextMenu.RadioItemIndicator>, "style"> & StyleOverrideProps,
) {
  const { children, keepMounted = true, ...rest } = allProps;
  return (
    <StyledRadioItemIndicator keepMounted={keepMounted} {...rest}>
      {children ?? <CheckIcon />}
    </StyledRadioItemIndicator>
  );
}
RadioItemIndicator.displayName = "ContextMenuRadioItemIndicator";

const StyledCheckboxItemIndicator = withContext(
  BaseContextMenu.CheckboxItemIndicator,
  (v) => [...resolveSlotStyles(menuRecipe.slots.indicator, v), chrome.indicator],
  "ContextMenuCheckboxItemIndicator",
);

function CheckboxItemIndicator(
  allProps: Omit<React.ComponentProps<typeof BaseContextMenu.CheckboxItemIndicator>, "style"> & StyleOverrideProps,
) {
  const { children, keepMounted = true, ...rest } = allProps;
  return (
    <StyledCheckboxItemIndicator keepMounted={keepMounted} {...rest}>
      {children ?? <CheckIcon />}
    </StyledCheckboxItemIndicator>
  );
}
CheckboxItemIndicator.displayName = "ContextMenuCheckboxItemIndicator";

/**
 * ContextMenu — Base UI's context menu wearing the menu slot recipe: the
 * Trigger is an area that opens the menu at the pointer on right-click (or
 * long-press on touch); the Portal → Positioner → Popup chain, typeahead and
 * keyboard navigation are the engine's (highlight styles key off its
 * `data-highlighted`). `<ContextMenu.Root size variant>` resolves the recipe
 * once; every part inherits it through context and composes via `render`.
 * Portal and Positioner stay unstyled engine parts.
 */
export const ContextMenu = {
  Root: withRootProvider(BaseContextMenu.Root, "ContextMenuRoot"),
  Trigger: BaseContextMenu.Trigger,
  Portal: BaseContextMenu.Portal,
  Positioner: BaseContextMenu.Positioner,
  Popup: withContext(
    BaseContextMenu.Popup,
    (v) => [...resolveSlotStyles(menuRecipe.slots.content, v), chrome.content],
    "ContextMenuPopup",
  ),
  Item: withContext(
    BaseContextMenu.Item,
    (v) => [...resolveSlotStyles(menuRecipe.slots.item, v), chrome.item],
    "ContextMenuItem",
  ),
  SubmenuRoot: BaseContextMenu.SubmenuRoot,
  SubmenuTrigger: withContext(
    BaseContextMenu.SubmenuTrigger,
    (v) => [...resolveSlotStyles(menuRecipe.slots.item, v), chrome.item],
    "ContextMenuSubmenuTrigger",
  ),
  ItemText: withContext("span", "itemText", "ContextMenuItemText"),
  Group: BaseContextMenu.Group,
  GroupLabel: withContext(BaseContextMenu.GroupLabel, "itemGroupLabel", "ContextMenuGroupLabel"),
  RadioGroup: BaseContextMenu.RadioGroup,
  RadioItem: withContext(
    BaseContextMenu.RadioItem,
    (v) => [...resolveSlotStyles(menuRecipe.slots.item, v), chrome.item],
    "ContextMenuRadioItem",
  ),
  RadioItemIndicator,
  CheckboxItem: withContext(
    BaseContextMenu.CheckboxItem,
    (v) => [...resolveSlotStyles(menuRecipe.slots.item, v), chrome.item],
    "ContextMenuCheckboxItem",
  ),
  CheckboxItemIndicator,
  ItemCommand: withContext(
    "span",
    (v) => [...resolveSlotStyles(menuRecipe.slots.itemCommand, v), chrome.itemCommand],
    "ContextMenuItemCommand",
  ),
  Separator: withContext(BaseContextMenu.Separator, "separator", "ContextMenuSeparator"),
};
```
