Context Menu
The shadcn/ui Context Menu with menus that grow out of the cursor and smooth highlights — plus an animated React right-click menu block built with Motion and Radix that opens from the click point, staggers its items and glides a highlight between them.
- Drop-in shadcn API
- Right-click & long-press
- Sub-menus
- Checkbox & radio items
- Motion block
"use client";
import * as React from "react";
import { Copy, Download, FileImage, FolderInput, Link2, Pencil, Share2, Star, Trash2 } from "lucide-react";
import { toast } from "sonner";
import {
AnimatedContextMenu,
AnimatedContextMenuCheckboxItem,
AnimatedContextMenuContent,
AnimatedContextMenuItem,
AnimatedContextMenuLabel,
AnimatedContextMenuRadioGroup,
AnimatedContextMenuRadioItem,
AnimatedContextMenuSeparator,
AnimatedContextMenuSub,
AnimatedContextMenuSubContent,
AnimatedContextMenuSubTrigger,
AnimatedContextMenuTrigger,
} from "@/components/dusk/context-menu/animated-context-menu";
export default function AnimatedContextMenuDemo() {
const [starred, setStarred] = React.useState(false);
const [view, setView] = React.useState("grid");
return (
<AnimatedContextMenu>
<AnimatedContextMenuTrigger
tabIndex={0}
className="group flex w-full max-w-sm flex-col items-center gap-3 rounded-xl border border-dashed p-8 text-center outline-none select-none transition-colors focus-visible:ring-[3px] focus-visible:ring-ring/50 data-[state=open]:border-foreground/25 data-[state=open]:bg-accent/40"
>
<span className="flex size-14 items-center justify-center rounded-xl border bg-card text-muted-foreground transition-colors group-data-[state=open]:text-foreground">
<FileImage className="size-6" aria-hidden />
</span>
<span>
<span className="block text-sm font-medium">aurora-hero.png</span>
<span className="block text-xs text-muted-foreground">Right-click anywhere in this box</span>
</span>
</AnimatedContextMenuTrigger>
<AnimatedContextMenuContent className="w-60">
<AnimatedContextMenuLabel>aurora-hero.png</AnimatedContextMenuLabel>
<AnimatedContextMenuItem icon={<Pencil />} shortcut="F2" onSelect={() => toast("Renaming…")}>
Rename
</AnimatedContextMenuItem>
<AnimatedContextMenuItem icon={<Copy />} shortcut="⌘D" onSelect={() => toast("Duplicated")}>
Duplicate
</AnimatedContextMenuItem>
<AnimatedContextMenuSub>
<AnimatedContextMenuSubTrigger icon={<Share2 />}>Share</AnimatedContextMenuSubTrigger>
<AnimatedContextMenuSubContent>
<AnimatedContextMenuItem icon={<Link2 />} onSelect={() => toast("Link copied")}>
Copy link
</AnimatedContextMenuItem>
<AnimatedContextMenuItem icon={<Download />} onSelect={() => toast("Downloading…")}>
Download
</AnimatedContextMenuItem>
<AnimatedContextMenuItem icon={<FolderInput />} onSelect={() => toast("Moved")}>
Move to…
</AnimatedContextMenuItem>
</AnimatedContextMenuSubContent>
</AnimatedContextMenuSub>
<AnimatedContextMenuSeparator />
<AnimatedContextMenuCheckboxItem
checked={starred}
onCheckedChange={setStarred}
onSelect={(event) => event.preventDefault()}
>
<span className="flex items-center gap-2">
Starred
<Star className={starred ? "size-3.5 fill-primary text-primary" : "size-3.5 text-muted-foreground"} aria-hidden />
</span>
</AnimatedContextMenuCheckboxItem>
<AnimatedContextMenuSeparator />
<AnimatedContextMenuLabel>View as</AnimatedContextMenuLabel>
<AnimatedContextMenuRadioGroup value={view} onValueChange={setView}>
<AnimatedContextMenuRadioItem value="grid" onSelect={(event) => event.preventDefault()}>
Grid
</AnimatedContextMenuRadioItem>
<AnimatedContextMenuRadioItem value="list" onSelect={(event) => event.preventDefault()}>
List
</AnimatedContextMenuRadioItem>
</AnimatedContextMenuRadioGroup>
<AnimatedContextMenuSeparator />
<AnimatedContextMenuItem icon={<Trash2 />} shortcut="⌫" variant="destructive" onSelect={() => toast.error("Moved to trash")}>
Move to trash
</AnimatedContextMenuItem>
</AnimatedContextMenuContent>
</AnimatedContextMenu>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/context-menu.json1. Install the dependencies.
npm install @radix-ui/react-context-menu lucide-react2. Copy the source into
components/ui/context-menu.tsx.context-menu.tsx "use client" import * as React from "react" import * as ContextMenuPrimitive from "@radix-ui/react-context-menu" import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react" import { cn } from "@/lib/utils" /** * DuskUI Context Menu — the shadcn/ui Context Menu with DuskUI motion. * * Same parts, props and data-slot attributes as shadcn, plus: * - Menus grow out of the cursor: the scale origin follows Radix's transform * origin (the click point), with a short ease-out, and close quicker than * they open. * - Highlighted items ease their background in; destructive items tint red. * - Check and radio indicators fade in when an item is selected. * - Under `prefers-reduced-motion` menus only fade. * CSS only (tw-animate-css). Radix handles right-click and long-press, * focus, typeahead, arrow keys, sub-menus and aria. */ function ContextMenu({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Root>) { return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} /> } /** The area that opens the menu on right-click (or long-press on touch). */ function ContextMenuTrigger({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) { return ( <ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} /> ) } /** Groups related items. Purely semantic (role="group"). */ function ContextMenuGroup({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Group>) { return ( <ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} /> ) } /** Portals content to `document.body`. Content already portals itself. */ function ContextMenuPortal({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) { return ( <ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} /> ) } /** Wraps a sub-menu: a SubTrigger and its SubContent. */ function ContextMenuSub({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) { return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} /> } /** Holds radio items; only one can be selected. Use `value` / `onValueChange`. */ function ContextMenuRadioGroup({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) { return ( <ContextMenuPrimitive.RadioGroup data-slot="context-menu-radio-group" {...props} /> ) } const surface = [ "z-50 min-w-[8rem] overflow-x-hidden overflow-y-auto rounded-lg border bg-popover p-1 text-popover-foreground", "origin-(--radix-context-menu-content-transform-origin)", "shadow-md ease-out", "data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[state=open]:duration-150", "data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=closed]:duration-100", "motion-reduce:data-[state=open]:zoom-in-100 motion-reduce:data-[state=closed]:zoom-out-100", ] /** The menu surface. Portalled and positioned at the pointer. */ function ContextMenuContent({ className, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Content>) { return ( <ContextMenuPrimitive.Portal> <ContextMenuPrimitive.Content data-slot="context-menu-content" className={cn( surface, "max-h-(--radix-context-menu-content-available-height)", className )} {...props} /> </ContextMenuPrimitive.Portal> ) } const itemBase = [ "relative flex cursor-default items-center gap-2 rounded-md px-2 py-1.5 text-sm outline-hidden select-none", "transition-[color,background-color] duration-150 ease-out motion-reduce:transition-none", "focus:bg-accent focus:text-accent-foreground", "data-[disabled]:pointer-events-none data-[disabled]:opacity-50", "[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground", ] /** A menu action. `onSelect` fires on click, Enter or Space and closes the menu. */ function ContextMenuItem({ className, inset, variant = "default", ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Item> & { /** Indent to line up with items that have an indicator or icon. */ inset?: boolean /** `destructive` tints the item (and its icon) red. */ variant?: "default" | "destructive" }) { return ( <ContextMenuPrimitive.Item data-slot="context-menu-item" data-inset={inset} data-variant={variant} className={cn( itemBase, "data-[inset]:pl-8", "data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:*:[svg]:!text-destructive", className )} {...props} /> ) } /** The item that opens a sub-menu (hover, click, or the arrow key toward it). */ function ContextMenuSubTrigger({ className, inset, children, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & { inset?: boolean }) { return ( <ContextMenuPrimitive.SubTrigger data-slot="context-menu-sub-trigger" data-inset={inset} className={cn( itemBase, "group/sub data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground", className )} {...props} > {children} <ChevronRightIcon className="ml-auto size-4" /> </ContextMenuPrimitive.SubTrigger> ) } /** The nested menu surface. */ function ContextMenuSubContent({ className, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) { return ( <ContextMenuPrimitive.Portal> <ContextMenuPrimitive.SubContent data-slot="context-menu-sub-content" className={cn( surface, "data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2", "motion-reduce:data-[side=left]:slide-in-from-right-0 motion-reduce:data-[side=right]:slide-in-from-left-0", className )} {...props} /> </ContextMenuPrimitive.Portal> ) } /** The check / radio indicator slot. */ const indicatorSlot = "pointer-events-none absolute left-2 flex size-3.5 items-center justify-center" /** The indicator mounts when the item becomes checked, so it fades in. */ const indicatorPop = "flex items-center justify-center animate-in fade-in-0 duration-150 ease-out motion-reduce:animate-none" /** A toggleable item with a check mark. Use `checked` / `onCheckedChange`. */ function ContextMenuCheckboxItem({ className, children, checked, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) { return ( <ContextMenuPrimitive.CheckboxItem data-slot="context-menu-checkbox-item" className={cn(itemBase, "py-1.5 pr-2 pl-8", className)} checked={checked} {...props} > <span className={indicatorSlot}> <ContextMenuPrimitive.ItemIndicator className={indicatorPop}> <CheckIcon className="size-4 !text-foreground" /> </ContextMenuPrimitive.ItemIndicator> </span> {children} </ContextMenuPrimitive.CheckboxItem> ) } /** One choice inside a ContextMenuRadioGroup. */ function ContextMenuRadioItem({ className, children, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) { return ( <ContextMenuPrimitive.RadioItem data-slot="context-menu-radio-item" className={cn(itemBase, "py-1.5 pr-2 pl-8", className)} {...props} > <span className={indicatorSlot}> <ContextMenuPrimitive.ItemIndicator className={indicatorPop}> <CircleIcon className="size-2 fill-current !text-foreground" /> </ContextMenuPrimitive.ItemIndicator> </span> {children} </ContextMenuPrimitive.RadioItem> ) } /** A non-interactive heading for a group of items. */ function ContextMenuLabel({ className, inset, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Label> & { inset?: boolean }) { return ( <ContextMenuPrimitive.Label data-slot="context-menu-label" data-inset={inset} className={cn( "px-2 py-1.5 text-xs font-medium text-muted-foreground data-[inset]:pl-8", className )} {...props} /> ) } /** A thin divider between groups. */ function ContextMenuSeparator({ className, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) { return ( <ContextMenuPrimitive.Separator data-slot="context-menu-separator" className={cn("-mx-1 my-1 h-px bg-border", className)} {...props} /> ) } /** Right-aligned keyboard hint, e.g. ⌘C. Visual only; wire the shortcut yourself. */ function ContextMenuShortcut({ className, ...props }: React.ComponentProps<"span">) { return ( <span data-slot="context-menu-shortcut" className={cn( "ml-auto font-mono text-[0.7rem] tracking-widest text-muted-foreground/80", className )} {...props} /> ) } export { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuCheckboxItem, ContextMenuRadioItem, ContextMenuLabel, ContextMenuSeparator, ContextMenuShortcut, ContextMenuGroup, ContextMenuPortal, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuRadioGroup, }
Same exports and props as the shadcn/ui Context Menu (including inset and variant="destructive"), so it drops into existing code. Animations are CSS (tw-animate-css), so the base needs no Motion.
Usage
import {
ContextMenu,
ContextMenuContent,
ContextMenuItem,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuTrigger,
} from "@/components/ui/context-menu"
export function FileMenu() {
return (
<ContextMenu>
<ContextMenuTrigger className="rounded-lg border p-8">Right-click me</ContextMenuTrigger>
<ContextMenuContent className="w-52">
<ContextMenuItem>
Copy
<ContextMenuShortcut>⌘C</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuItem>Rename</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem variant="destructive">Delete</ContextMenuItem>
</ContextMenuContent>
</ContextMenu>
)
}Examples
Default
Right-click (or long-press on touch) the area. The menu scales out of the exact point you clicked (Radix's transform origin) and closes faster than it opened. Includes shortcuts, a disabled item, a sub-menu, checkbox and radio items whose indicators fade in, and a destructive item.
"use client";
import * as React from "react";
import {
ContextMenu,
ContextMenuCheckboxItem,
ContextMenuContent,
ContextMenuItem,
ContextMenuLabel,
ContextMenuRadioGroup,
ContextMenuRadioItem,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuTrigger,
} from "@/components/ui/context-menu";
export default function ContextMenuBasicDemo() {
const [bookmarks, setBookmarks] = React.useState(true);
const [fullUrls, setFullUrls] = React.useState(false);
const [person, setPerson] = React.useState("ada");
return (
<ContextMenu>
<ContextMenuTrigger
tabIndex={0}
className="flex h-40 w-full max-w-sm items-center justify-center rounded-xl border border-dashed text-sm text-muted-foreground outline-none select-none focus-visible:ring-[3px] focus-visible:ring-ring/50 data-[state=open]:border-foreground/25 data-[state=open]:text-foreground"
>
Right-click here (or long-press)
</ContextMenuTrigger>
<ContextMenuContent className="w-60">
<ContextMenuItem inset>
Back
<ContextMenuShortcut>⌘[</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuItem inset disabled>
Forward
<ContextMenuShortcut>⌘]</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuItem inset>
Reload
<ContextMenuShortcut>⌘R</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuSub>
<ContextMenuSubTrigger inset>More tools</ContextMenuSubTrigger>
<ContextMenuSubContent className="w-44">
<ContextMenuItem>Save page as…</ContextMenuItem>
<ContextMenuItem>Create shortcut…</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem>Developer tools</ContextMenuItem>
</ContextMenuSubContent>
</ContextMenuSub>
<ContextMenuSeparator />
<ContextMenuCheckboxItem checked={bookmarks} onCheckedChange={setBookmarks}>
Show bookmarks bar
</ContextMenuCheckboxItem>
<ContextMenuCheckboxItem checked={fullUrls} onCheckedChange={setFullUrls}>
Show full URLs
</ContextMenuCheckboxItem>
<ContextMenuSeparator />
<ContextMenuLabel inset>People</ContextMenuLabel>
<ContextMenuRadioGroup value={person} onValueChange={setPerson}>
<ContextMenuRadioItem value="ada">Ada Kim</ContextMenuRadioItem>
<ContextMenuRadioItem value="sam">Sam Patel</ContextMenuRadioItem>
</ContextMenuRadioGroup>
<ContextMenuSeparator />
<ContextMenuItem inset variant="destructive">
Clear history
</ContextMenuItem>
</ContextMenuContent>
</ContextMenu>
);
}Blocks
Ready-made variations composed from the base component with Motion. Each installs on its own and pulls in its dependencies automatically.
Animated Context Menu
Opens from the cursor point while items fade in one after another. A highlight pill glides between items as you hover or arrow through them (a shared Motion layoutId per menu level), check marks draw themselves, radio dots scale in, separators draw across and sub-menus slide out the same way. Call event.preventDefault() in onSelect to keep the menu open while toggling.
"use client";
import * as React from "react";
import { Copy, Download, FileImage, FolderInput, Link2, Pencil, Share2, Star, Trash2 } from "lucide-react";
import { toast } from "sonner";
import {
AnimatedContextMenu,
AnimatedContextMenuCheckboxItem,
AnimatedContextMenuContent,
AnimatedContextMenuItem,
AnimatedContextMenuLabel,
AnimatedContextMenuRadioGroup,
AnimatedContextMenuRadioItem,
AnimatedContextMenuSeparator,
AnimatedContextMenuSub,
AnimatedContextMenuSubContent,
AnimatedContextMenuSubTrigger,
AnimatedContextMenuTrigger,
} from "@/components/dusk/context-menu/animated-context-menu";
export default function AnimatedContextMenuDemo() {
const [starred, setStarred] = React.useState(false);
const [view, setView] = React.useState("grid");
return (
<AnimatedContextMenu>
<AnimatedContextMenuTrigger
tabIndex={0}
className="group flex w-full max-w-sm flex-col items-center gap-3 rounded-xl border border-dashed p-8 text-center outline-none select-none transition-colors focus-visible:ring-[3px] focus-visible:ring-ring/50 data-[state=open]:border-foreground/25 data-[state=open]:bg-accent/40"
>
<span className="flex size-14 items-center justify-center rounded-xl border bg-card text-muted-foreground transition-colors group-data-[state=open]:text-foreground">
<FileImage className="size-6" aria-hidden />
</span>
<span>
<span className="block text-sm font-medium">aurora-hero.png</span>
<span className="block text-xs text-muted-foreground">Right-click anywhere in this box</span>
</span>
</AnimatedContextMenuTrigger>
<AnimatedContextMenuContent className="w-60">
<AnimatedContextMenuLabel>aurora-hero.png</AnimatedContextMenuLabel>
<AnimatedContextMenuItem icon={<Pencil />} shortcut="F2" onSelect={() => toast("Renaming…")}>
Rename
</AnimatedContextMenuItem>
<AnimatedContextMenuItem icon={<Copy />} shortcut="⌘D" onSelect={() => toast("Duplicated")}>
Duplicate
</AnimatedContextMenuItem>
<AnimatedContextMenuSub>
<AnimatedContextMenuSubTrigger icon={<Share2 />}>Share</AnimatedContextMenuSubTrigger>
<AnimatedContextMenuSubContent>
<AnimatedContextMenuItem icon={<Link2 />} onSelect={() => toast("Link copied")}>
Copy link
</AnimatedContextMenuItem>
<AnimatedContextMenuItem icon={<Download />} onSelect={() => toast("Downloading…")}>
Download
</AnimatedContextMenuItem>
<AnimatedContextMenuItem icon={<FolderInput />} onSelect={() => toast("Moved")}>
Move to…
</AnimatedContextMenuItem>
</AnimatedContextMenuSubContent>
</AnimatedContextMenuSub>
<AnimatedContextMenuSeparator />
<AnimatedContextMenuCheckboxItem
checked={starred}
onCheckedChange={setStarred}
onSelect={(event) => event.preventDefault()}
>
<span className="flex items-center gap-2">
Starred
<Star className={starred ? "size-3.5 fill-primary text-primary" : "size-3.5 text-muted-foreground"} aria-hidden />
</span>
</AnimatedContextMenuCheckboxItem>
<AnimatedContextMenuSeparator />
<AnimatedContextMenuLabel>View as</AnimatedContextMenuLabel>
<AnimatedContextMenuRadioGroup value={view} onValueChange={setView}>
<AnimatedContextMenuRadioItem value="grid" onSelect={(event) => event.preventDefault()}>
Grid
</AnimatedContextMenuRadioItem>
<AnimatedContextMenuRadioItem value="list" onSelect={(event) => event.preventDefault()}>
List
</AnimatedContextMenuRadioItem>
</AnimatedContextMenuRadioGroup>
<AnimatedContextMenuSeparator />
<AnimatedContextMenuItem icon={<Trash2 />} shortcut="⌫" variant="destructive" onSelect={() => toast.error("Moved to trash")}>
Move to trash
</AnimatedContextMenuItem>
</AnimatedContextMenuContent>
</AnimatedContextMenu>
);
}$ npx shadcn@latest add https://duskui.com/r/animated-context-menu.json1. Install the dependencies.
npm install motion @radix-ui/react-context-menu lucide-react2. Copy the source into
components/dusk/context-menu/animated-context-menu.tsx.animated-context-menu.tsx "use client"; import * as React from "react"; import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"; import { AnimatePresence, motion, useReducedMotion, type Transition, type Variants } from "motion/react"; import { ChevronRight } from "lucide-react"; import { ContextMenuShortcut, ContextMenuTrigger } from "@/components/ui/context-menu"; import { cn } from "@/lib/utils"; const pillSpring: Transition = { type: "spring", stiffness: 520, damping: 38, mass: 0.6 }; type RootContextValue = { open: boolean; reduceMotion: boolean }; const RootContext = React.createContext<RootContextValue | null>(null); /** Each surface (the menu and every sub-menu) has its own highlight. */ type SurfaceContextValue = { id: string; active: string | null; setActive: (id: string | null) => void }; const SurfaceContext = React.createContext<SurfaceContextValue | null>(null); type SubContextValue = { open: boolean }; const SubContext = React.createContext<SubContextValue | null>(null); function useRoot() { const context = React.useContext(RootContext); if (!context) throw new Error("AnimatedContextMenu parts must be used inside <AnimatedContextMenu>."); return context; } function useSurface() { const context = React.useContext(SurfaceContext); if (!context) throw new Error("AnimatedContextMenu items must be inside AnimatedContextMenuContent or SubContent."); return context; } function useSurfaceState() { const id = React.useId(); const [active, setActive] = React.useState<string | null>(null); return React.useMemo(() => ({ id, active, setActive }), [id, active]); } export type AnimatedContextMenuProps = React.ComponentProps<typeof ContextMenuPrimitive.Root>; /** * A context menu that opens from the exact point you right-clicked. * Items cascade in, a highlight pill glides between them as you hover or * arrow through, check marks draw themselves and sub-menus slide out the same * way. Built on Radix Context Menu, so long-press on touch, focus, typeahead, * arrow keys, Escape and aria all work. Under reduced motion it fades and the * pill jumps. */ export function AnimatedContextMenu({ onOpenChange, children, ...props }: AnimatedContextMenuProps) { const reduceMotion = useReducedMotion() ?? false; // Radix Context Menu is uncontrolled; mirror its state so AnimatePresence can run the exit. const [open, setOpen] = React.useState(false); const value = React.useMemo(() => ({ open, reduceMotion }), [open, reduceMotion]); return ( <RootContext.Provider value={value}> <ContextMenuPrimitive.Root onOpenChange={(next) => { setOpen(next); onOpenChange?.(next); }} {...props} > {children} </ContextMenuPrimitive.Root> </RootContext.Provider> ); } /** The area that opens the menu on right-click or long-press. */ export const AnimatedContextMenuTrigger = ContextMenuTrigger; function surfaceVariants(reduceMotion: boolean, stagger: number, fromX = 0): Variants { return reduceMotion ? { closed: { opacity: 0, transition: { duration: 0.1 } }, open: { opacity: 1, transition: { duration: 0.15 } }, } : { closed: { opacity: 0, scale: 0.96, x: fromX, transition: { duration: 0.1, ease: "easeIn" } }, open: { opacity: 1, scale: 1, x: 0, transition: { duration: 0.18, ease: "easeOut", staggerChildren: stagger, delayChildren: 0.02 }, }, }; } const surfaceClass = cn( "z-50 min-w-52 overflow-x-hidden overflow-y-auto rounded-xl border bg-popover p-1.5 text-popover-foreground shadow-lg outline-none", "origin-(--radix-context-menu-content-transform-origin)" ); export interface AnimatedContextMenuContentProps extends Omit<React.ComponentProps<typeof ContextMenuPrimitive.Content>, "forceMount" | "asChild" | "children"> { children?: React.ReactNode; /** Delay between items as they cascade in, in seconds. */ stagger?: number; } /** The menu surface. Scales out of the cursor point and staggers its items in. */ export function AnimatedContextMenuContent({ className, stagger = 0.03, children, onPointerLeave, ...props }: AnimatedContextMenuContentProps) { const { open, reduceMotion } = useRoot(); const surface = useSurfaceState(); const { setActive } = surface; return ( <AnimatePresence onExitComplete={() => setActive(null)}> {open && ( // forceMount hands mounting to AnimatePresence so the exit animation can play. <ContextMenuPrimitive.Portal key="menu" forceMount> <ContextMenuPrimitive.Content forceMount asChild onPointerLeave={(event) => { onPointerLeave?.(event); setActive(null); }} {...props} > <motion.div className={cn(surfaceClass, "max-h-(--radix-context-menu-content-available-height)", className)} variants={surfaceVariants(reduceMotion, stagger)} initial="closed" animate="open" exit="closed" > <SurfaceContext.Provider value={surface}>{children}</SurfaceContext.Provider> </motion.div> </ContextMenuPrimitive.Content> </ContextMenuPrimitive.Portal> )} </AnimatePresence> ); } function useItemVariants(): Variants { const { reduceMotion } = useRoot(); return reduceMotion ? { closed: { opacity: 0, transition: { duration: 0.1 } }, open: { opacity: 1 } } : { closed: { opacity: 0, x: -4, transition: { duration: 0.1 } }, open: { opacity: 1, x: 0, transition: { duration: 0.18, ease: "easeOut" } }, }; } /** Shared item chrome: the gliding pill, optional icon and shortcut. */ function useItemHighlight() { const itemId = React.useId(); const { id, active, setActive } = useSurface(); const { reduceMotion } = useRoot(); return { isActive: active === itemId, activate: () => setActive(itemId), pill: (variant: "default" | "destructive" = "default") => ( <motion.span aria-hidden layoutId={`${id}-pill`} className={cn( "absolute inset-0 rounded-lg", variant === "destructive" ? "bg-destructive/15" : "bg-accent" )} transition={reduceMotion ? { duration: 0 } : pillSpring} /> ), }; } const itemClass = cn( "relative flex cursor-default items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-sm outline-none select-none", "transition-colors duration-150 data-[disabled]:pointer-events-none data-[disabled]:opacity-50", "[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4" ); export interface AnimatedContextMenuItemProps extends Omit<React.ComponentProps<typeof ContextMenuPrimitive.Item>, "asChild"> { /** Leading icon. */ icon?: React.ReactNode; /** Trailing keyboard hint, e.g. "⌘C". Visual only. */ shortcut?: React.ReactNode; /** `destructive` tints the item and its highlight red. */ variant?: "default" | "destructive"; } /** A menu action. `onSelect` fires on click, Enter or Space and closes the menu. */ export function AnimatedContextMenuItem({ className, children, icon, shortcut, variant = "default", onFocus, ...props }: AnimatedContextMenuItemProps) { const variants = useItemVariants(); const { isActive, activate, pill } = useItemHighlight(); return ( <ContextMenuPrimitive.Item asChild // Radix focuses items on hover and arrow keys, so focus drives the pill. onFocus={(event) => { onFocus?.(event); activate(); }} {...props} > <motion.div variants={variants} data-variant={variant} className={cn( itemClass, variant === "destructive" ? "text-destructive" : "text-foreground/90 data-[highlighted]:text-foreground", className )} > {isActive && pill(variant)} {icon && ( <span aria-hidden className={cn( "relative flex transition-colors duration-150", variant === "destructive" ? "text-destructive" : isActive ? "text-foreground" : "text-muted-foreground" )} > {icon} </span> )} <span className="relative flex-1 truncate">{children}</span> {shortcut && <ContextMenuShortcut className="relative">{shortcut}</ContextMenuShortcut>} </motion.div> </ContextMenuPrimitive.Item> ); } export interface AnimatedContextMenuCheckboxItemProps extends Omit<React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>, "asChild" | "checked"> { checked?: boolean; shortcut?: React.ReactNode; } /** A toggle with a check mark that draws itself in. Use `checked` / `onCheckedChange`. */ export function AnimatedContextMenuCheckboxItem({ className, children, checked = false, shortcut, onFocus, ...props }: AnimatedContextMenuCheckboxItemProps) { const variants = useItemVariants(); const { reduceMotion } = useRoot(); const { isActive, activate, pill } = useItemHighlight(); return ( <ContextMenuPrimitive.CheckboxItem asChild checked={checked} onFocus={(event) => { onFocus?.(event); activate(); }} {...props} > <motion.div variants={variants} className={cn(itemClass, "text-foreground/90 data-[highlighted]:text-foreground", className)}> {isActive && pill()} <span aria-hidden className={cn( "relative flex size-4 items-center justify-center rounded-[5px] border transition-colors duration-150", checked ? "border-primary/50 bg-primary/15" : "border-white/15" )} > <svg viewBox="0 0 16 16" className="size-3 !text-primary" fill="none"> <motion.path d="M3.5 8.5l3 3 6-7" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" initial={false} animate={{ pathLength: checked ? 1 : 0, opacity: checked ? 1 : 0 }} transition={reduceMotion ? { duration: 0 } : { duration: 0.22, ease: "easeOut" }} /> </svg> </span> <span className="relative flex-1 truncate">{children}</span> {shortcut && <ContextMenuShortcut className="relative">{shortcut}</ContextMenuShortcut>} </motion.div> </ContextMenuPrimitive.CheckboxItem> ); } /** Holds radio items; only one can be selected. Use `value` / `onValueChange`. */ export const AnimatedContextMenuRadioGroup = ContextMenuPrimitive.RadioGroup; /** One choice inside AnimatedContextMenuRadioGroup. Its dot springs in. */ export function AnimatedContextMenuRadioItem({ className, children, onFocus, ...props }: Omit<React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>, "asChild">) { const variants = useItemVariants(); const { reduceMotion } = useRoot(); const { isActive, activate, pill } = useItemHighlight(); return ( <ContextMenuPrimitive.RadioItem asChild onFocus={(event) => { onFocus?.(event); activate(); }} {...props} > <motion.div variants={variants} className={cn(itemClass, "group/radio text-foreground/90 data-[highlighted]:text-foreground", className)} > {isActive && pill()} <span aria-hidden className="relative flex size-4 items-center justify-center rounded-full border border-white/15 transition-colors duration-150 group-data-[state=checked]/radio:border-primary/50" > <ContextMenuPrimitive.ItemIndicator asChild> <motion.span className="size-2 rounded-full bg-primary" initial={reduceMotion ? { opacity: 0 } : { scale: 0 }} animate={reduceMotion ? { opacity: 1 } : { scale: 1 }} transition={reduceMotion ? { duration: 0 } : { type: "spring", duration: 0.2, bounce: 0.1 }} /> </ContextMenuPrimitive.ItemIndicator> </span> <span className="relative flex-1 truncate">{children}</span> </motion.div> </ContextMenuPrimitive.RadioItem> ); } /** A small heading for a group of items. Cascades in with the items. */ export function AnimatedContextMenuLabel({ className, ...props }: Omit<React.ComponentProps<typeof motion.div>, "variants">) { const variants = useItemVariants(); return ( <ContextMenuPrimitive.Label asChild> <motion.div variants={variants} className={cn("px-2.5 pt-1.5 pb-1 text-xs font-medium text-muted-foreground", className)} {...props} /> </ContextMenuPrimitive.Label> ); } /** A divider between groups. Draws in from the left as the menu opens. */ export function AnimatedContextMenuSeparator({ className, ...props }: Omit<React.ComponentProps<typeof motion.div>, "variants">) { const { reduceMotion } = useRoot(); return ( <ContextMenuPrimitive.Separator asChild> <motion.div variants={ reduceMotion ? { closed: { opacity: 0, transition: { duration: 0.1 } }, open: { opacity: 1 } } : { closed: { scaleX: 0, opacity: 0, transition: { duration: 0.1 } }, open: { scaleX: 1, opacity: 1, transition: { duration: 0.2, ease: "easeOut" } }, } } className={cn("-mx-1.5 my-1.5 h-px origin-left bg-border", className)} {...props} /> </ContextMenuPrimitive.Separator> ); } /** Groups related items (role="group"). */ export const AnimatedContextMenuGroup = ContextMenuPrimitive.Group; /** Wraps a sub-menu: an AnimatedContextMenuSubTrigger and its AnimatedContextMenuSubContent. */ export function AnimatedContextMenuSub({ open: openProp, defaultOpen = false, onOpenChange, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) { const [internalOpen, setInternalOpen] = React.useState(defaultOpen); const open = openProp ?? internalOpen; return ( <SubContext.Provider value={{ open }}> <ContextMenuPrimitive.Sub open={open} onOpenChange={(next) => { if (openProp === undefined) setInternalOpen(next); onOpenChange?.(next); }} {...props} /> </SubContext.Provider> ); } /** The item that opens a sub-menu. Stays highlighted while its sub-menu is open. */ export function AnimatedContextMenuSubTrigger({ className, children, icon, onFocus, ...props }: Omit<React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger>, "asChild"> & { icon?: React.ReactNode }) { const variants = useItemVariants(); const { isActive, activate, pill } = useItemHighlight(); const sub = React.useContext(SubContext); const lit = isActive || !!sub?.open; return ( <ContextMenuPrimitive.SubTrigger asChild onFocus={(event) => { onFocus?.(event); activate(); }} {...props} > <motion.div variants={variants} className={cn(itemClass, "text-foreground/90 data-[state=open]:text-foreground data-[highlighted]:text-foreground", className)} > {isActive && pill()} {!isActive && sub?.open && <span aria-hidden className="absolute inset-0 rounded-lg bg-accent/70" />} {icon && ( <span aria-hidden className={cn("relative flex transition-colors duration-150", lit ? "text-foreground" : "text-muted-foreground")}> {icon} </span> )} <span className="relative flex-1 truncate">{children}</span> <ChevronRight aria-hidden className={cn( "relative text-muted-foreground transition-transform duration-200 motion-reduce:transition-none", sub?.open && "translate-x-0.5 text-foreground" )} /> </motion.div> </ContextMenuPrimitive.SubTrigger> ); } /** The nested menu surface. Slides out of its trigger and staggers its items. */ export function AnimatedContextMenuSubContent({ className, stagger = 0.025, children, onPointerLeave, ...props }: Omit<React.ComponentProps<typeof ContextMenuPrimitive.SubContent>, "forceMount" | "asChild" | "children"> & { children?: React.ReactNode; stagger?: number; }) { const { reduceMotion } = useRoot(); const sub = React.useContext(SubContext); const surface = useSurfaceState(); const { setActive } = surface; if (!sub) throw new Error("AnimatedContextMenuSubContent must be inside <AnimatedContextMenuSub>."); return ( <AnimatePresence onExitComplete={() => setActive(null)}> {sub.open && ( <ContextMenuPrimitive.Portal key="sub" forceMount> <ContextMenuPrimitive.SubContent forceMount asChild sideOffset={6} alignOffset={-6} onPointerLeave={(event) => { onPointerLeave?.(event); setActive(null); }} {...props} > <motion.div className={cn(surfaceClass, "min-w-44", className)} variants={surfaceVariants(reduceMotion, stagger, -8)} initial="closed" animate="open" exit="closed" > <SurfaceContext.Provider value={surface}>{children}</SurfaceContext.Provider> </motion.div> </ContextMenuPrimitive.SubContent> </ContextMenuPrimitive.Portal> )} </AnimatePresence> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| AnimatedContextMenu | Radix Root props | — | onOpenChange, modal, dir. |
| AnimatedContextMenuTrigger | Radix Trigger props | — | The right-click area. disabled turns the menu off. |
| AnimatedContextMenuContent | Radix Content props & { stagger?: number } | — | stagger is the delay between items in seconds (default 0.03). |
| AnimatedContextMenuItem | Radix Item props & { icon?, shortcut?, variant? } | — | An action. variant="destructive" tints it red. |
| AnimatedContextMenuCheckboxItem | Radix CheckboxItem props & { checked?, shortcut? } | — | A toggle with a self-drawing check mark. |
| AnimatedContextMenuRadioGroup / RadioItem | Radix props | — | Single choice with a dot that scales in. |
| AnimatedContextMenuSub / SubTrigger / SubContent | Radix props & { icon? } / { stagger? } | — | A nested menu with its own gliding highlight. |
| AnimatedContextMenuLabel / Separator / Group | Radix props | — | Headings, dividers and groups that animate with the items. |
API Reference
Same parts as shadcn/ui: ContextMenu, Trigger, Content, Item, CheckboxItem, RadioGroup, RadioItem, Label, Separator, Shortcut, Group, Portal, Sub, SubTrigger and SubContent (all prefixed ContextMenu). Each forwards the Radix props.
| Prop | Type | Default | Description |
|---|---|---|---|
| onOpenChange / modal | (open: boolean) => void / boolean | — / true | On ContextMenu. Radix Context Menu is uncontrolled. |
| disabled | boolean | — | Turn the menu off for this area (on ContextMenuTrigger). |
| onSelect | (event: Event) => void | — | Fires on click, Enter or Space; preventDefault() keeps the menu open (on items). |
| variant | "default" | "destructive" | "default" | Red destructive item (on ContextMenuItem). |
| inset | boolean | — | Indent to align with items that have an indicator (Item, Label, SubTrigger). |
| checked / onCheckedChange | boolean / (checked: boolean) => void | — | On ContextMenuCheckboxItem. |
| value / onValueChange | string / (value: string) => void | — | On ContextMenuRadioGroup. |
Accessibility
- Built on Radix Context Menu:
role="menu"with menuitem, menuitemcheckbox and menuitemradio roles, roving focus and typeahead. - Opens with right-click, long-press on touch, or the context-menu key / Shift+F10 — give the trigger
tabIndex={0}(as the demos do) so keyboard users can focus it. - Arrow keys move between items, Right/Left open and close sub-menus, Enter/Space select and Escape closes.
- In the Animated Context Menu the highlight follows keyboard focus as well as the pointer, and an open sub-menu keeps its trigger highlighted.
- Under prefers-reduced-motion menus only fade, the cascade is removed and the highlight jumps instead of gliding.