HextaUI

Dropdown menu: Controlled

Pass open and onOpenChange. The second argument says why the menu changed, such as a trigger press, an item press or Escape. Items with closeOnClick={false} keep it open.

Open: false · last reason: none

"use client"

import * as React from "react"

import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"

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

  return (
    <div className="flex flex-col items-center gap-3">
      <DropdownMenu
        open={open}
        onOpenChange={(next, details) => {
          setOpen(next)
          setReason(details.reason)
        }}
      >
        <DropdownMenuTrigger render={<Button variant="outline" />}>
          Controlled
        </DropdownMenuTrigger>
        <DropdownMenuContent>
          <DropdownMenuItem>Closes the menu</DropdownMenuItem>
          <DropdownMenuItem closeOnClick={false}>Stays open</DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
      <p className="text-sm text-muted-foreground">
        Open: {String(open)} · last reason: {reason}
      </p>
    </div>
  )
}

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

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

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

Props in this example

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

PropTypeDefault
open
boolean–
onOpenChangedetails.reason says what caused the change.
(open: boolean, details) => void–
PropTypeDefault
render
ReactElement | (props, state) => ReactElement<button>
PropTypeDefault
closeOnClick
booleantrue

Every prop is in the Dropdown menu API reference.

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