---
title: "Context Menu · UI SDK — 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/ui-sdk/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: UI SDK
- Also available for: [Ark UI](https://stylexblocks.com/components/ark-ui/context-menu.md), [Base UI](https://stylexblocks.com/components/base-ui/context-menu.md)
- Category: Display
- Variants: subtle, solid
- Sizes: sm, md
- HTML page: https://stylexblocks.com/components/ui-sdk/context-menu/

## Install

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

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

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/ui-sdk/context-menu.json

## Usage

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

export function Example() {
  return (
    // Right-click (or long-press) the trigger area to open the menu at the
    // pointer; give it a tab stop so Shift+F10 opens it from the keyboard.
    // Content is a native popover in the top layer: no Portal or Positioner.
    <ContextMenu.Root size="md" onAction={(value) => console.log(value)}>
      <ContextMenu.Trigger tabIndex={0}>Right-click here</ContextMenu.Trigger>
      <ContextMenu.Content>
        <ContextMenu.Item value="reload">
          <ContextMenu.ItemText>Reload</ContextMenu.ItemText>
          <ContextMenu.ItemCommand>⌘R</ContextMenu.ItemCommand>
        </ContextMenu.Item>
        <ContextMenu.Separator />
        <ContextMenu.CheckboxItem value="bookmarks" defaultChecked>
          <ContextMenu.ItemIndicator />
          <ContextMenu.ItemText>Show bookmarks</ContextMenu.ItemText>
        </ContextMenu.CheckboxItem>
      </ContextMenu.Content>
    </ContextMenu.Root>
  );
}
```

## Source

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

```tsx
import * as stylex from "@stylexjs/stylex";
import {
  Menu as UiSdkMenu,
  MenuCheckboxItem,
  MenuContent,
  MenuContextTrigger,
  MenuGroup,
  MenuGroupLabel,
  MenuItem,
  MenuItemIndicator,
  MenuRadioGroup,
  MenuRadioItem,
  MenuSeparator,
  MenuShortcut,
  MenuSub,
  MenuSubContent,
  MenuSubTrigger,
} from "@ui-sdk/react/menu";
import { createSlotRecipeContext } from "#lib/ui-sdk/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`). UI SDK menu content is a native
// popover in the top layer that keeps the browser's popover border, margin
// and background, so the surface resets them here (the recipe sizes set the
// padding).
const chrome = stylex.create({
  content: {
    "--menu-z-index": zIndices.dropdown,
    margin: 0,
    borderWidth: 0,
    backgroundColor: semanticColors.bgPanel,
    borderRadius: semanticRadii.panel,
    boxShadow: semanticShadows.overlay,
  },
  item: {
    paddingBlock: spacing._1,
    color: {
      default: null,
      ":is([data-destructive])": semanticColors.fgError,
    },
    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 itemStyles = (v: Record<string, string>) => [
  ...resolveSlotStyles(menuRecipe.slots.item, v),
  chrome.item,
];
const contentStyles = (v: Record<string, string>) => [
  ...resolveSlotStyles(menuRecipe.slots.content, v),
  chrome.content,
];

const StyledItemIndicator = withContext(
  MenuItemIndicator,
  (v) => [...resolveSlotStyles(menuRecipe.slots.indicator, v), chrome.indicator],
  "ContextMenuItemIndicator",
);

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

/**
 * ContextMenu — UI SDK's menu opened from a `ContextTrigger` area, wearing
 * the menu slot recipe: right-click (or long-press on touch, or Shift+F10 /
 * the context-menu key on a focused area) opens the menu at the pointer, and
 * right-clicking elsewhere in the area repositions it. The content is a
 * native popover in the browser's top layer, so there is no Portal or
 * Positioner. Typeahead, arrow-key navigation, submenus and dismissal come
 * from the engine; highlight styles key off its `data-highlighted`, and the
 * open trigger area carries `data-open`. `<ContextMenu.Root size variant>`
 * resolves the recipe once; every part inherits it through context and
 * composes via `render`. One `ItemIndicator` serves checkbox and radio items.
 */
export const ContextMenu = {
  Root: withRootProvider(UiSdkMenu, "ContextMenuRoot"),
  Trigger: MenuContextTrigger,
  Content: withContext(MenuContent, contentStyles, "ContextMenuContent"),
  Item: withContext(MenuItem, itemStyles, "ContextMenuItem"),
  SubmenuRoot: MenuSub,
  SubmenuTrigger: withContext(MenuSubTrigger, itemStyles, "ContextMenuSubmenuTrigger"),
  SubmenuContent: withContext(MenuSubContent, contentStyles, "ContextMenuSubmenuContent"),
  ItemText: withContext("span", "itemText", "ContextMenuItemText"),
  Group: MenuGroup,
  GroupLabel: withContext(MenuGroupLabel, "itemGroupLabel", "ContextMenuGroupLabel"),
  CheckboxItem: withContext(MenuCheckboxItem, itemStyles, "ContextMenuCheckboxItem"),
  RadioGroup: MenuRadioGroup,
  RadioItem: withContext(MenuRadioItem, itemStyles, "ContextMenuRadioItem"),
  ItemIndicator,
  ItemCommand: withContext(
    MenuShortcut,
    (v) => [...resolveSlotStyles(menuRecipe.slots.itemCommand, v), chrome.itemCommand],
    "ContextMenuItemCommand",
  ),
  Separator: withContext(MenuSeparator, "separator", "ContextMenuSeparator"),
};
```
