← Components

Containment · Material 3: Menus (context)

Context menu

The same Menu, opened at the pointer by right-click or long press. On touch, a ring fills around the finger first.

Examples and variants

Basic

Right-click the area.

Right-click (or long-press) here
Example
function ContextMenuArea() {
  return (
    <ContextMenu>
      <ContextMenuTrigger className="flex h-32 w-full max-w-xs items-center justify-center rounded-(--shape-lg) bg-canvas text-sm text-muted-foreground shadow-1">
        Right-click (or long-press) here
      </ContextMenuTrigger>
      <ContextMenuContent>
        <DropdownMenuItem>
          Copy <DropdownMenuShortcut>⌘C</DropdownMenuShortcut>
        </DropdownMenuItem>
        <DropdownMenuItem>Duplicate</DropdownMenuItem>
        <DropdownMenuSeparator />
        <DropdownMenuItem tone="danger">
          <TrashIcon /> Delete
        </DropdownMenuItem>
      </ContextMenuContent>
    </ContextMenu>
  )
}

Spec drawing

Measured from the live component at default density. Each code maps to the token that sets it; change the token and the drawing follows.

Install

With the CLI

The shadcn CLI only delivers files: it copies our code from the Isotopi registry into your project and installs the packages it uses. Add the foundation once, then the component.

Terminal
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/context-menu.json
npx shadcn@latest add https://isotopi.com/r/dropdown-menu.json

By hand

No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.

  1. Install the packages it uses.

    Terminal
    npm install @base-ui/react cn lucide-react
  2. Copy these 2 files to the same paths in your project. Imports use the @/ alias for your project root.

    • components/ui/dropdown-menu.tsxdropdown-menu
      components/ui/dropdown-menu.tsx
      "use client"
      
      import * as React from "react"
      import { Menu as MenuPrimitive } from "@base-ui/react/menu"
      import { ChevronRightIcon } from "lucide-react"
      import { cn } from "cn"
      import { layoutTop } from "@/lib/motion/layout-offset"
      import { usePortalMotion } from "@/lib/overlay"
      
      function DropdownMenu(props: MenuPrimitive.Root.Props) {
        return <MenuPrimitive.Root {...props} />
      }
      
      function DropdownMenuTrigger(props: MenuPrimitive.Trigger.Props) {
        return <MenuPrimitive.Trigger data-slot="menu-trigger" {...props} />
      }
      
      /*
        On phones (< 640px) a root menu presents as a bottom sheet with a scrim
        (component-model.md §3: one Menu, adaptive presentation). Submenus and
        presentation="popover" keep the anchored popover everywhere.
      */
      function DropdownMenuContent({
        className,
        children,
        side,
        align,
        sideOffset = 6,
        presentation = "auto",
        ...props
      }: MenuPrimitive.Popup.Props &
        Pick<MenuPrimitive.Positioner.Props, "side" | "align" | "sideOffset"> & {
          presentation?: "auto" | "popover"
        }) {
        const submenu = (props as Record<string, unknown>)["data-submenu"] !== undefined
        const sheet = presentation === "auto" && !submenu
        const ref = React.useRef<HTMLDivElement>(null)
        usePortalMotion(ref)
        return (
          <MenuPrimitive.Portal>
            {sheet ? <MenuPrimitive.Backdrop className="menu-sheet-scrim fixed inset-0 z-dropdown" /> : null}
            <MenuPrimitive.Positioner
              className={cn("z-dropdown", sheet && "menu-sheet-positioner")}
              side={side}
              align={align}
              sideOffset={sideOffset}
            >
              <MenuPrimitive.Popup
                ref={ref}
                data-slot="menu-content"
                data-sheet={sheet || undefined}
                className={cn(
                  "overlay-surface overlay-grow z-dropdown min-w-(--menu-min-width) rounded-(--menu-corner) p-(--menu-padding) text-sm text-foreground",
                  className
                )}
                {...props}
              >
                <MenuHighlight>{children}</MenuHighlight>
              </MenuPrimitive.Popup>
            </MenuPrimitive.Positioner>
          </MenuPrimitive.Portal>
        )
      }
      
      export function MenuHighlight({ children }: { children: React.ReactNode }) {
        const ref = React.useRef<HTMLDivElement>(null)
        const [box, setBox] = React.useState({ top: 0, height: 0, stretch: false, danger: false })
        const [ready, setReady] = React.useState(false)
      
        React.useLayoutEffect(() => {
          const root = ref.current
          if (!root) return
          const read = () => {
            const item = root.querySelector<HTMLElement>("[data-highlighted]")
            if (!item) return
            const motion = root.closest<HTMLElement>("[data-motion]")?.dataset.motion
            setBox({
              top: layoutTop(item, root),
              height: item.offsetHeight,
              stretch: item.hasAttribute("data-popup-open") && motion !== "calm" && motion !== "still",
              danger: item.dataset.tone === "danger",
            })
            setReady(true)
          }
          read()
          const observer = new MutationObserver(read)
          observer.observe(root, {
            subtree: true,
            attributes: true,
            attributeFilter: ["data-highlighted", "data-popup-open", "data-motion"],
          })
          const resize = new ResizeObserver(read)
          resize.observe(root)
          return () => {
            observer.disconnect()
            resize.disconnect()
          }
        }, [])
      
        return (
          <div ref={ref} className="relative">
            {ready ? (
              <span
                aria-hidden
                className={cn(
                  "menu-pill pointer-events-none absolute left-1 rounded-(--menu-item-corner) bg-(--menu-item-highlight) transition-[background-color] duration-(--duration-fast)",
                  box.danger && "bg-(--color-danger-subtle)"
                )}
                style={{
                  top: box.top,
                  height: box.height,
                  right: box.stretch ? "calc(var(--motion-distance-lg) * -1)" : "var(--space-1)",
                }}
              />
            ) : null}
            {children}
          </div>
        )
      }
      
      function DropdownMenuItem({
        className,
        tone = "neutral",
        ...props
      }: MenuPrimitive.Item.Props & { tone?: "neutral" | "danger" }) {
        return (
          <MenuPrimitive.Item
            data-slot="menu-item"
            data-tone={tone}
            className={cn(
              "menu-item relative z-[1] flex cursor-default items-center gap-inline-sm rounded-(--menu-item-corner) text-sm outline-none data-disabled:text-(--menu-item-label-disabled)",
              tone === "danger" && "text-(--color-danger-fg)",
              className
            )}
            {...props}
          />
        )
      }
      
      function DropdownMenuCheckboxItem({ className, ...props }: MenuPrimitive.CheckboxItem.Props) {
        return (
          <MenuPrimitive.CheckboxItem
            data-slot="menu-item"
            className={cn(
              "menu-item relative z-[1] flex cursor-default items-center rounded-(--menu-item-corner) text-sm outline-none",
              className
            )}
            {...props}
          />
        )
      }
      
      function DropdownMenuRadioGroup(props: MenuPrimitive.RadioGroup.Props) {
        return <MenuPrimitive.RadioGroup {...props} />
      }
      
      function DropdownMenuRadioItem({ className, ...props }: MenuPrimitive.RadioItem.Props) {
        return (
          <MenuPrimitive.RadioItem
            data-slot="menu-item"
            className={cn(
              "menu-item relative z-[1] flex cursor-default items-center rounded-(--menu-item-corner) text-sm outline-none",
              className
            )}
            {...props}
          />
        )
      }
      
      function DropdownMenuLabel({ className, ...props }: MenuPrimitive.GroupLabel.Props) {
        return (
          <MenuPrimitive.GroupLabel
            className={cn("px-2 py-1 text-xs text-muted-foreground", className)}
            {...props}
          />
        )
      }
      
      function DropdownMenuSeparator({ className, ...props }: React.ComponentProps<"div">) {
        return <div aria-hidden className={cn("h-stack-sm", className)} {...props} />
      }
      
      function DropdownMenuSub(props: MenuPrimitive.SubmenuRoot.Props) {
        return <MenuPrimitive.SubmenuRoot {...props} />
      }
      
      function DropdownMenuSubTrigger({ className, children, ...props }: MenuPrimitive.SubmenuTrigger.Props) {
        return (
          <MenuPrimitive.SubmenuTrigger
            data-slot="menu-sub-trigger"
            className={cn(
              "menu-item relative z-[1] flex w-full cursor-default items-center gap-inline-sm rounded-(--menu-item-corner) text-sm outline-none",
              className
            )}
            {...props}
          >
            {children}
            <ChevronRightIcon className="ml-auto size-icon-sm text-muted-foreground" />
          </MenuPrimitive.SubmenuTrigger>
        )
      }
      
      function DropdownMenuSubContent(props: MenuPrimitive.Popup.Props) {
        return <DropdownMenuContent data-submenu="" {...props} />
      }
      
      function DropdownMenuShortcut({ className, ...props }: React.ComponentProps<"span">) {
        return <span className={cn("ml-auto text-xs text-muted-foreground", className)} {...props} />
      }
      
      export {
        DropdownMenu,
        DropdownMenuTrigger,
        DropdownMenuContent,
        DropdownMenuItem,
        DropdownMenuCheckboxItem,
        DropdownMenuRadioGroup,
        DropdownMenuRadioItem,
        DropdownMenuLabel,
        DropdownMenuSeparator,
        DropdownMenuSub,
        DropdownMenuSubTrigger,
        DropdownMenuSubContent,
        DropdownMenuShortcut,
      }
      
    • components/ui/context-menu.tsxcontext-menu
      components/ui/context-menu.tsx
      "use client"
      
      import * as React from "react"
      import { ContextMenu as ContextMenuPrimitive } from "@base-ui/react/context-menu"
      import { cn } from "cn"
      import { usePortalMotion } from "@/lib/overlay"
      import { MenuHighlight } from "@/components/ui/dropdown-menu"
      
      /*
        Context menu: the same Menu, opened at the pointer by right-click or a long
        press (touch). Items are the Menu's items (DropdownMenuItem, Sub, etc.).
        On touch, a ring fills around the finger during the long press.
      */
      function ContextMenu(props: ContextMenuPrimitive.Root.Props) {
        return <ContextMenuPrimitive.Root {...props} />
      }
      
      function ContextMenuTrigger({ className, onPointerDown, ...props }: ContextMenuPrimitive.Trigger.Props) {
        const [ring, setRing] = React.useState<{ x: number; y: number; id: number } | null>(null)
        return (
          <ContextMenuPrimitive.Trigger
            data-slot="context-menu-trigger"
            className={cn("relative", className)}
            onPointerDown={(event) => {
              onPointerDown?.(event)
              if (event.pointerType !== "touch") return
              const box = event.currentTarget.getBoundingClientRect()
              setRing({ x: event.clientX - box.left, y: event.clientY - box.top, id: Date.now() })
            }}
            onPointerUp={() => setRing(null)}
            onPointerCancel={() => setRing(null)}
            {...props}
          >
            {props.children}
            {ring ? (
              <span
                key={ring.id}
                aria-hidden
                className="context-ring pointer-events-none absolute size-(--context-ring-size) -translate-1/2 rounded-full"
                style={{ left: ring.x, top: ring.y }}
                onAnimationEnd={() => setRing(null)}
              />
            ) : null}
          </ContextMenuPrimitive.Trigger>
        )
      }
      
      function ContextMenuContent({ className, children, ...props }: ContextMenuPrimitive.Popup.Props) {
        const ref = React.useRef<HTMLDivElement>(null)
        usePortalMotion(ref)
        return (
          <ContextMenuPrimitive.Portal>
            <ContextMenuPrimitive.Positioner className="z-dropdown">
              <ContextMenuPrimitive.Popup
                ref={ref}
                data-slot="menu-content"
                className={cn(
                  "overlay-surface overlay-grow z-dropdown min-w-(--menu-min-width) rounded-(--menu-corner) p-(--menu-padding) text-sm text-foreground",
                  className
                )}
                {...props}
              >
                <MenuHighlight>{children}</MenuHighlight>
              </ContextMenuPrimitive.Popup>
            </ContextMenuPrimitive.Positioner>
          </ContextMenuPrimitive.Portal>
        )
      }
      
      export { ContextMenu, ContextMenuTrigger, ContextMenuContent }
      

Imports

What the examples on this page import:

Imports
import { CopyIcon, FileIcon, MoonIcon, PlusIcon, SettingsIcon, TrashIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Calendar, type CalendarRange } from "@/components/ui/calendar"
import { Carousel } from "@/components/ui/carousel"
import { CommandDialog, type CommandItem } from "@/components/ui/command"
import { ContextMenu, ContextMenuContent, ContextMenuTrigger } from "@/components/ui/context-menu"
import { DatePicker } from "@/components/ui/date-picker"
import { DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuShortcut } from "@/components/ui/dropdown-menu"
import { Kbd, KbdGroup } from "@/components/ui/kbd"
import { Menubar, MenubarMenu, MenubarTrigger } from "@/components/ui/menubar"
import { Search } from "@/components/ui/search"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { TimePicker } from "@/components/ui/time-picker"

Anatomy

  1. 1Trigger area · Any element.
  2. 2Menu · Same tokens and items as Menu.
  3. 3Long-press ring · --context-ring-size, --context-ring.

Props

PropTypeDefaultDescription
childrenDropdownMenuItem etc.—Use the Menu's items.

Tokens

Every visual spec is a component token in styles/tokens/components.css, pointing at a semantic token. Change a token to restyle the component; themes change the semantic layer.

TokenPoints toLightDark
--menu-containervar(--surface-container-raised)oklch(1 0 0)oklch(0.22 0 0)
--menu-cornervar(--shape-md)14pxsame
--menu-paddingvar(--space-inset-overlay)8pxsame
--menu-elevationvar(--elevation-2)0 1px 1px -0.5px oklch(0.22 0.01 260 / 6%), 0 3px 3px -1.5px oklch(0.22 0.01 260 / 6%), 0 6px 6px -3px oklch(0.22 0.01 260 / 6%), 0 12px 12px -6px oklch(0.22 0.01 260 / 6%), 0 24px 24px -12px oklch(0.22 0.01 260 / 6%)0 4px 12px oklch(0 0 0 / 40%), 0 12px 28px oklch(0 0 0 / 35%)
--menu-item-heightvar(--size-row-sm)32pxsame
--menu-item-padding-xvar(--space-inset-control-x-sm)8pxsame
--menu-item-cornervar(--shape-sm)8pxsame
--menu-item-highlightvar(--color-bg-hover)oklch(0.965 0.005 95)oklch(0.22 0 0)
--menu-item-label-disabledvar(--color-fg-disabled)oklch(0.62 0.01 95)oklch(0.53 0 0)
--menu-item-dangervar(--color-danger-fg)oklch(0.48 0.18 25)oklch(0.78 0.14 22)
--menu-min-widthvar(--layout-menu-min)180pxsame
--context-ring-sizevar(--space-12)48pxsame
--context-ringvar(--color-border-focus)oklch(0.6 0.17 248)oklch(0.72 0.14 245)

Motion

TriggerWhat happensTokens
OpenGrows from the pointer; on touch, the ring fills during the press.--duration-fast, --duration-fill

Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.

Accessibility

  • Shift+F10 or the menu key opens it on the focused element.
  • Never the only way to reach an action.

Usage

Do

  • Use for shortcuts on items.

Don’t

  • Don't hide essential actions only here.

Code

components/ui/context-menu.tsx
"use client"

import * as React from "react"
import { ContextMenu as ContextMenuPrimitive } from "@base-ui/react/context-menu"
import { cn } from "cn"
import { usePortalMotion } from "@/lib/overlay"
import { MenuHighlight } from "@/components/ui/dropdown-menu"

/*
  Context menu: the same Menu, opened at the pointer by right-click or a long
  press (touch). Items are the Menu's items (DropdownMenuItem, Sub, etc.).
  On touch, a ring fills around the finger during the long press.
*/
function ContextMenu(props: ContextMenuPrimitive.Root.Props) {
  return <ContextMenuPrimitive.Root {...props} />
}

function ContextMenuTrigger({ className, onPointerDown, ...props }: ContextMenuPrimitive.Trigger.Props) {
  const [ring, setRing] = React.useState<{ x: number; y: number; id: number } | null>(null)
  return (
    <ContextMenuPrimitive.Trigger
      data-slot="context-menu-trigger"
      className={cn("relative", className)}
      onPointerDown={(event) => {
        onPointerDown?.(event)
        if (event.pointerType !== "touch") return
        const box = event.currentTarget.getBoundingClientRect()
        setRing({ x: event.clientX - box.left, y: event.clientY - box.top, id: Date.now() })
      }}
      onPointerUp={() => setRing(null)}
      onPointerCancel={() => setRing(null)}
      {...props}
    >
      {props.children}
      {ring ? (
        <span
          key={ring.id}
          aria-hidden
          className="context-ring pointer-events-none absolute size-(--context-ring-size) -translate-1/2 rounded-full"
          style={{ left: ring.x, top: ring.y }}
          onAnimationEnd={() => setRing(null)}
        />
      ) : null}
    </ContextMenuPrimitive.Trigger>
  )
}

function ContextMenuContent({ className, children, ...props }: ContextMenuPrimitive.Popup.Props) {
  const ref = React.useRef<HTMLDivElement>(null)
  usePortalMotion(ref)
  return (
    <ContextMenuPrimitive.Portal>
      <ContextMenuPrimitive.Positioner className="z-dropdown">
        <ContextMenuPrimitive.Popup
          ref={ref}
          data-slot="menu-content"
          className={cn(
            "overlay-surface overlay-grow z-dropdown min-w-(--menu-min-width) rounded-(--menu-corner) p-(--menu-padding) text-sm text-foreground",
            className
          )}
          {...props}
        >
          <MenuHighlight>{children}</MenuHighlight>
        </ContextMenuPrimitive.Popup>
      </ContextMenuPrimitive.Positioner>
    </ContextMenuPrimitive.Portal>
  )
}

export { ContextMenu, ContextMenuTrigger, ContextMenuContent }