DocumentationMenu
Menu
Actions, context and submenus. One keyboard-friendly menu.
Getting started
Install the package
Use React 19 and import the package stylesheet once in your app’s global CSS. The bundled styles are built for Tailwind CSS 4.
bun add @rentnerkev/menu@import '@rentnerkev/menu/tailwind.css';Async actions: pending, retry and success#
Plain action items opt into onSelectAsync(event): Promise<void>; existing onSelect and onAction stay synchronous. Either synchronous callback can call preventDefault() to cancel the async operation before it starts. The item shows pendingLabel with aria-busy and ignores duplicate activation for its full stable submenu ID path, even across rerenders and close/reopen cycles. Different paths remain independent. Links, checkboxes and radio callbacks keep their synchronous behavior.
import { Menu, type MenuItem } from '@rentnerkev/menu'
import { useRef, useState } from 'react'
export default function AsyncSaveMenu() {
const attempts = useRef(0)
const [status, setStatus] = useState('No save yet')
const items: MenuItem[] = [{
id: 'save',
label: 'Save changes',
pendingLabel: 'Saving changes...',
errorLabel: 'Saving failed. Try again.',
onSelectAsync: async () => {
const attempt = ++attempts.current
await new Promise<void>((resolve) => setTimeout(resolve, 800))
if (attempt === 1) throw new Error('Local demonstration failure')
setStatus('Changes saved')
},
}]
return (
<div>
<Menu
ariaLabel="Save actions"
trigger="Save actions"
items={items}
onActionError={() => setStatus('Saving failed. Try again.')}
/>
<p role="status">{status}</p>
</div>
)
}Installation and shared styling#
Install with bun add @rentnerkev/menu and provide React 19 plus react-dom 19 as peer dependencies. Import the Tailwind stylesheet once in your application CSS; it includes the shared theme tokens. The separate theme.css export contains tokens only. Translate ariaLabel, item labels, descriptions and trigger text in your application; Menu has no messages or locale prop.
@import 'tailwindcss';
@import '@rentnerkev/menu/tailwind.css';
:root {
--rentner-accent: #0369a1;
--rentner-surface: #ffffff;
--rentner-foreground: #0f172a;
}Checkboxes, radio groups and indeterminate state#
Checkbox and radio items are controlled: update checked in their onCheckedChange callbacks. Checkbox checked also accepts indeterminate; selecting that state emits true. A radio callback runs only when the item was not already checked. Give related radio items the same name, and use closeOnSelect: false to keep the menu open while changing preferences.
import { Menu } from '@rentnerkev/menu'
import type { MenuItem } from '@rentnerkev/menu'
import { useState } from 'react'
export default function ViewPreferences() {
const [checked, setChecked] = useState<boolean | 'indeterminate'>(
'indeterminate',
)
const [density, setDensity] = useState<'compact' | 'comfortable'>(
'comfortable',
)
const items: MenuItem[] = [
{
id: 'selection',
type: 'checkbox',
label: 'Select all',
checked,
onCheckedChange: setChecked,
closeOnSelect: false,
},
{ id: 'density', type: 'label', label: 'Density' },
{
id: 'compact',
type: 'radio',
name: 'density',
label: 'Compact',
checked: density === 'compact',
onCheckedChange: () => setDensity('compact'),
closeOnSelect: false,
},
{
id: 'comfortable',
type: 'radio',
name: 'density',
label: 'Comfortable',
checked: density === 'comfortable',
onCheckedChange: () => setDensity('comfortable'),
closeOnSelect: false,
},
]
return <Menu ariaLabel="View preferences" trigger="View" items={items} />
}Native links and selection cancellation#
A type: link item renders a real anchor with href, target, rel and download. Browser actions such as opening a new tab remain native. onSelect and onAction receive MenuSelectEvent; preventDefault() cancels the original navigation and keeps the menu open. closeOnSelect: false keeps the menu open without cancelling navigation. Disabled links cannot activate. Validate untrusted destinations in your application.
import { Menu } from '@rentnerkev/menu'
import { useState } from 'react'
export default function ResourceLinks() {
const [blocked, setBlocked] = useState(false)
return (
<div>
<Menu
ariaLabel="Resource links"
items={[
{
id: 'docs',
type: 'link',
label: 'Documentation',
href: 'https://packages.rentner.dev/docs/menu',
target: '_blank',
rel: 'noopener noreferrer',
},
{
id: 'download',
type: 'link',
label: 'Download report',
href: '/report.csv',
download: 'report.csv',
},
{
id: 'review',
type: 'link',
label: 'Review before leaving',
href: '/review',
onSelect: (event) => {
event.preventDefault()
setBlocked(true)
},
},
]}
/>
{blocked && (
<p role="status">Navigation cancelled. The menu stays open.</p>
)}
</div>
)
}Controlled state and shared defaults#
Use open and onOpenChange together, or defaultOpen for internal state. MenuProvider supplies customization such as controlSize, side, align, loop, classNames and modal. Nested providers inherit unspecified values and class-name slots; each menu can override them. onEscapeKeyDown can preventDefault() to cancel Escape dismissal.
import { Menu, MenuProvider } from '@rentnerkev/menu'
import { useState } from 'react'
export default function ControlledActions() {
const [open, setOpen] = useState(false)
return (
<MenuProvider
controlSize="sm"
align="end"
loop
classNames={{ item: 'text-sm' }}
>
<Menu
ariaLabel="Controlled actions"
trigger="Actions"
open={open}
onOpenChange={setOpen}
items={[{ id: 'refresh', label: 'Refresh' }]}
/>
<button type="button" onClick={() => setOpen(true)}>
Open actions
</button>
</MenuProvider>
)
}Mouse hover opening#
Since v1.0.1, set openOnHover to open a nonmodal Menu with a mouse while keeping the current focus. hoverOpenDelayMs defaults to 100 and hoverCloseDelayMs to 150; entering a menu surface cancels closing. Click, touch and keyboard activation stay available. Keyboard activation takes over from hover. Escape closes the popup; focus stays on an outside control or returns to the trigger when navigating inside. Touch, pen and compatibility mouse events do not trigger hover. Controlled menus use open with onOpenChange. Disabled triggers, preventDefault() and modal behavior are respected.
import { Menu } from '@rentnerkev/menu'
export default function HoverActions() {
return (
<Menu
ariaLabel="Host actions"
trigger="Actions"
openOnHover
hoverOpenDelayMs={100}
hoverCloseDelayMs={150}
items={[{ id: 'edit', label: 'Edit host' }]}
/>
)
}asChild: one custom native button#
By default trigger is button content, so never nest another button inside it. Set asChild when trigger is a single native button or a component forwarding props and its ref to one. Child handlers run before triggerProps handlers and menu behavior; preventDefault() cancels downstream handling. Child refs and triggerRef are composed, including React 19 callback-ref cleanup. Custom buttons keep their own styling.
import { Menu } from '@rentnerkev/menu'
import { useRef } from 'react'
export default function CustomTrigger() {
const childRef = useRef<HTMLButtonElement>(null)
const triggerRef = useRef<HTMLButtonElement>(null)
return (
<Menu
asChild
ariaLabel="Custom actions"
triggerRef={triggerRef}
triggerProps={{ className: 'border rounded px-3 py-2' }}
trigger={
<button ref={childRef} type="button">
Custom actions
</button>
}
items={[{ id: 'inspect', label: 'Inspect' }]}
/>
)
}Optional modality, dialog portals and RTL#
Menus are nonmodal by default. modal blocks background interaction and scrolling while open; an outside pointer closes the menu and consumes that click. Escape restores focus, while Tab and Shift+Tab close it and resume page navigation. For menus inside a native dialog, set portalContainer to an element inside that dialog so its focus layer is preserved. dir: rtl reverses submenu arrows and horizontal placement. Render labels as text and let the application translate them.
import { Menu } from '@rentnerkev/menu'
import { useState } from 'react'
export default function DialogActions() {
const [dialog, setDialog] = useState<HTMLDialogElement | null>(null)
return (
<div>
<button type="button" onClick={() => dialog?.showModal()}>
Open dialog
</button>
<dialog ref={setDialog} aria-label="Document settings">
<Menu
modal
dir="rtl"
ariaLabel="Document actions"
trigger="Actions"
portalContainer={dialog}
items={[
{ id: 'copy', label: 'Copy' },
{
id: 'more',
type: 'submenu',
label: 'More',
items: [{ id: 'details', label: 'Details' }],
},
]}
/>
<button type="button" onClick={() => dialog?.close()}>
Close dialog
</button>
</dialog>
</div>
)
}Separate dropdown and context positioning#
Since v1.1.0, MenuProvider accepts menu and contextMenu positioning defaults: side, align, sideOffset and collisionPadding. Precedence per property is local component, menu-type defaults, shared provider, then built-in defaults; nested providers merge each property. Keyboard opening uses the target rectangle; pointer opening uses the click or long-press coordinates. Without an explicit side, pointer context menus open right in LTR and left in RTL; an explicit side is physical. Nonmodal outside interactions dismiss a context menu even inside its original target while preserving native actions and focus. A long press suppresses its following compatibility click; later taps work normally.
import { ContextMenu, Menu, MenuProvider } from '@rentnerkev/menu'
import type { MenuPositioningProps } from '@rentnerkev/menu'
const contextPosition: MenuPositioningProps = {
align: 'start',
sideOffset: 8,
collisionPadding: 12,
}
export default function PositionedActions() {
const items = [{ id: 'inspect', label: 'Inspect' }]
return (
<MenuProvider
align="end"
menu={{ side: 'bottom', sideOffset: 6 }}
contextMenu={contextPosition}
>
<Menu ariaLabel="Toolbar actions" trigger="Actions" items={items} />
<ContextMenu ariaLabel="File actions" items={items}>
<button type="button">Right-click or press Shift+F10</button>
</ContextMenu>
</MenuProvider>
)
}Independent icons, selection marks and arrows#
Since v1.1.0, classNames.icon, indicator and submenuIndicator style action icons, checkbox/radio marks and submenu arrows independently. Icons inherit item text color; selection marks keep the accent color. Icons and marks retain separate space, including unchecked marks. When upgrading, also set classNames.icon if indicator previously styled icons. Replace icon selectors using [data-rentner-menu-indicator] with [data-rentner-menu-icon]; arrows expose [data-rentner-menu-submenu-indicator].
import { Menu } from '@rentnerkev/menu'
import { useState } from 'react'
export default function StyledIndicators() {
const [checked, setChecked] = useState(false)
return (
<Menu
ariaLabel="Display options"
trigger="Display"
classNames={{
icon: 'text-sky-700',
indicator: 'text-emerald-700',
submenuIndicator: 'text-violet-700',
}}
items={[
{
id: 'details',
type: 'checkbox',
label: 'Show details',
icon: <span aria-hidden="true">☰</span>,
checked,
onCheckedChange: setChecked,
closeOnSelect: false,
},
{
id: 'more',
type: 'submenu',
label: 'More',
items: [{ id: 'reset', label: 'Reset view' }],
},
]}
/>
)
}Typed menu design tokens#
Since v1.1.0, MenuStyle types nine CSS properties: --rentner-menu-content-min-width, -padding, -radius and -border-width, plus --rentner-menu-item-min-height, -padding-x, -padding-y, -radius and -gap. Pass style to a menu or provider, or set tokens through classNames.content. Explicit item tokens override controlSize defaults. Use tokens for predictable sizing instead of conflicting Tailwind utilities. Tokens inherit from the portal DOM container; use :root or a themed portalContainer. Forced-colors mode retains a visible system-color border.
import { Menu, MenuProvider } from '@rentnerkev/menu'
import type { MenuStyle } from '@rentnerkev/menu'
const menuStyle: MenuStyle = {
'--rentner-menu-content-min-width': '14rem',
'--rentner-menu-content-padding': '0.5rem',
'--rentner-menu-content-radius': '1rem',
'--rentner-menu-content-border-width': '0px',
'--rentner-menu-item-min-height': '2rem',
'--rentner-menu-item-padding-x': '0.75rem',
'--rentner-menu-item-padding-y': '0.375rem',
'--rentner-menu-item-radius': '0.5rem',
'--rentner-menu-item-gap': '0.5rem',
}
export default function CompactActions() {
return (
<MenuProvider controlSize="sm" style={menuStyle}>
<Menu
ariaLabel="File actions"
trigger="Actions"
items={[{ id: 'save', label: 'Save' }]}
/>
</MenuProvider>
)
}Canonical documentation and the optional MCP server#
The canonical public MCP endpoint is https://packages.rentner.dev/mcp. Configure it explicitly in a compatible client for read-only package documentation. https://packages.rentner.dev/llms.txt indexes the catalog, and https://packages.rentner.dev/ai/menu?locale=en returns the English Menu guide. These remote pages describe the website catalog; the local /ai helpers below describe your installed package. Neither installation nor importing /ai configures or connects an AI client.
export const menuDocumentation = {
mcp: 'https://packages.rentner.dev/mcp',
index: 'https://packages.rentner.dev/llms.txt',
guide: 'https://packages.rentner.dev/ai/menu?locale=en',
}Local AI helpers: metadata & guides#
Import the /ai entry in a local Node.js or Bun script. These synchronous, read-only helpers use node:fs to read the installed package without importing its UI. getPackageInfo() returns PackageInfo, including the installed version, public exports and peer dependencies. getPackageDocumentation() returns a PackageDocument with path and content; its default is usage, and readme selects README.md. Only these two packaged documents are accepted. Results describe your installed version, which can differ from this website.
import { getPackageDocumentation, getPackageInfo } from '@rentnerkev/menu/ai'
import type { PackageDocument, PackageInfo } from '@rentnerkev/menu/ai'
const info: PackageInfo = getPackageInfo()
const usage: PackageDocument = getPackageDocumentation()
const readme = getPackageDocumentation('readme')
console.log(info.name, info.version, info.exports, info.peerDependencies)
console.log(usage.path, usage.content)
console.log(readme.path, readme.content)Local AI helpers: public declarations#
getPackageApi() returns PackageApi with package, installed version, selected subpaths and declarations as PackageDocument objects. It reads public typed entries and their local declaration dependencies; /ai itself is excluded. Use subpath such as . or ./types to select a public entry. symbol validates that a name is exported by the selected entry; it does not trim declaration files to that symbol. Unknown subpaths, invalid names and names not exported by the selected entry throw errors. Callers cannot provide arbitrary file paths.
import { getPackageApi } from '@rentnerkev/menu/ai'
import type { PackageApi } from '@rentnerkev/menu/ai'
const api: PackageApi = getPackageApi()
const selected = getPackageApi({ subpath: '.', symbol: 'Menu' })
console.log(api.package, api.version, api.subpaths)
for (const declaration of selected.declarations) {
console.log(declaration.path, declaration.content)
}Local AI helpers: search & examples#
searchPackageDocumentation(query) searches README.md and docs/usage.md using a trimmed, case-insensitive literal query. It returns PackageSearchMatch objects with path, a one-based line number and matching text; an empty query returns an empty array. getPackageExamples() returns every fenced code block from the installed usage guide as a PackageExample with language and code. These helpers return text for your own tools; they do not execute examples or contact an AI service.
import { getPackageExamples, searchPackageDocumentation } from '@rentnerkev/menu/ai'
import type { PackageExample, PackageSearchMatch } from '@rentnerkev/menu/ai'
const matches: PackageSearchMatch[] = searchPackageDocumentation('Menu')
const examples: PackageExample[] = getPackageExamples()
for (const match of matches) {
console.log(match.path, match.line, match.text)
}
for (const example of examples) {
console.log(example.language, example.code)
}Docs for your AI tools
Connect a compatible MCP client to read package APIs, guides and examples. Public access, no account or API key required.
Remote access is optional: add this public URL yourself to your MCP client. Clients use Streamable HTTP; the configuration format may vary. The local package /ai helpers read the installed version in Node.js or Bun and never connect to this server automatically.
{
"mcpServers": {
"rentnerPackages": {
"url": "https://packages.rentner.dev/mcp"
}
}
}Tools: list_packages, read_package_docs, read_package_api, read_package_examples and search_package_docs.
TypeScript / v1.2.0
API & types
Published signatures, props and types for this version. Expand an entry to inspect its definition and available import paths.
PackageInfointerface
@rentnerkev/menu/ai
export interface PackageInfo {
name: string
version: string
description: string
license: string
homepage: string
repository: {
type: string
url: string
}
exports: Record<string, string | {
types?: string
import?: string
default?: string
}>
peerDependencies: Record<string, string>
}PackageDocumentinterface
@rentnerkev/menu/ai
export interface PackageDocument {
path: string
content: string
}PackageApiinterface
@rentnerkev/menu/ai
export interface PackageApi {
package: string
version: string
subpaths: Record<string, string>
declarations: PackageDocument[]
}PackageSearchMatchinterface
@rentnerkev/menu/ai
export interface PackageSearchMatch {
path: string
line: number
text: string
}PackageExampleinterface
@rentnerkev/menu/ai
export interface PackageExample {
language: string
code: string
}getPackageInfofunction
@rentnerkev/menu/ai
export function getPackageInfo(): PackageInfogetPackageDocumentationfunction
@rentnerkev/menu/ai
export function getPackageDocumentation(document?: 'readme' | 'usage'): PackageDocumentgetPackageApifunction
@rentnerkev/menu/ai
export function getPackageApi(options?: {
subpath?: string
symbol?: string
}): PackageApisearchPackageDocumentationfunction
@rentnerkev/menu/ai
export function searchPackageDocumentation(query: string): PackageSearchMatch[]getPackageExamplesfunction
@rentnerkev/menu/ai
export function getPackageExamples(): PackageExample[]