HextaUI

Context menu: Controlled

Pass open and onOpenChange to own the state. The second argument says why it changed, such as trigger-press, outside-press or escape-key. Items with closeOnClick={false} keep it open.

Controlled area

Open: false · last reason: —

"use client"

import * as React from "react"
import { IconCopy, IconScissors } from "@tabler/icons-react"

import {
  ContextMenu,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuTrigger,
} from "@/components/ui/context-menu"

export function ContextMenuControlled() {
  const [open, setOpen] = React.useState(false)
  const [reason, setReason] = React.useState("—")

  return (
    <div className="flex w-full max-w-sm flex-col gap-2">
      <ContextMenu
        open={open}
        onOpenChange={(next, details) => {
          setOpen(next)
          setReason(details.reason)
        }}
      >
        <ContextMenuTrigger className="flex h-40 w-full items-center justify-center rounded-xl border border-dashed text-sm text-muted-foreground">
          Controlled area
        </ContextMenuTrigger>
        <ContextMenuContent>
          <ContextMenuItem>
            <IconScissors />
            Cut
          </ContextMenuItem>
          <ContextMenuItem>
            <IconCopy />
            Copy
          </ContextMenuItem>
          <ContextMenuItem closeOnClick={false}>
            Stays open on click
          </ContextMenuItem>
        </ContextMenuContent>
      </ContextMenu>
      <p className="text-sm text-muted-foreground">
        Open: {String(open)} · last reason: {reason}
      </p>
    </div>
  )
}

This adds the example as components/examples/context-menu/controlled.tsx, together with the Context menu component and the HextaUI theme tokens it needs.

pnpm dlx shadcn@latest add https://hextaui.com/r/context-menu-controlled.json

To add only the component, follow the Context menu installation.

Props in this example

The Context menu props this example sets, from the API reference.

PropTypeDefault
open
boolean–
onOpenChangedetails.reason says what caused the change.
(open: boolean, details) => void–
PropTypeDefault
closeOnClick
booleantrue

Every prop is in the Context menu API reference.

See them all, with keyboard support and accessibility notes, on the Context menu page.