Back

Nested Menu

A hover-activated nested menu component for multi-level navigation with smooth animations.

Category
NavigationReact
CSS
shadcn

Manual

Create a file and paste the following code into it.

nested-menu.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
"use client";

import * as React from "react";
import { useState, useCallback, useRef, useEffect } from "react";
import * as PopoverPrimitive from "@radix-ui/react-popover";
import { cn } from "@/lib/cn";

// ============================================================================
// Types
// ============================================================================

export interface NestedMenuItem {
	/** Unique key for the item */
	key: string;
	/** Display label */
	label: string;
	/** Icon component */
	icon?: React.ComponentType<{ className?: string }>;
	/** Click handler */
	onSelect?: () => void;
	/** Whether this item has a submenu */
	hasSubmenu?: boolean;
	/** Submenu items (if hasSubmenu is true) */
	submenuItems?: NestedMenuItem[];
	/** Color variant */
	variant?: "default" | "danger";
	/** Additional className for custom styling */
	className?: string;
	/** Icon color (CSS color value) */
	iconColor?: string;
	/** Separator after this item */
	separator?: boolean;
}

export interface NestedMenuSectionProps {
	/** Section title */
	title?: string;
	/** Items in this section */
	items: NestedMenuItem[];
	/** Show divider after section */
	showDivider?: boolean;
}

// ============================================================================
// Hook: useNestedMenu
// ============================================================================

export function useNestedMenu() {
	const [isOpen, setIsOpen] = useState(false);
	const [itemRef, setItemRef] = useState<HTMLElement | null>(null);
	const timeoutRef = useRef<NodeJS.Timeout | null>(null);

	const handleMouseEnter = useCallback((e: React.MouseEvent<HTMLElement>) => {
		if (timeoutRef.current) {
			clearTimeout(timeoutRef.current);
			timeoutRef.current = null;
		}
		setItemRef(e.currentTarget as HTMLElement);
		setIsOpen(true);
	}, []);

	const handleMouseLeave = useCallback(() => {
		// Longer delay to allow moving to submenu
		timeoutRef.current = setTimeout(() => {
			setIsOpen(false);
		}, 300);
	}, []);

	const cancelClose = useCallback(() => {
		if (timeoutRef.current) {
			clearTimeout(timeoutRef.current);
			timeoutRef.current = null;
		}
	}, []);

	useEffect(() => {
		return () => {
			if (timeoutRef.current) {
				clearTimeout(timeoutRef.current);
			}
		};
	}, []);

	return {
		isOpen,
		setIsOpen,
		itemRef,
		handleMouseEnter,
		handleMouseLeave,
		cancelClose,
	};
}

// ============================================================================
// NestedMenuTooltip Component
// ============================================================================

export interface NestedMenuTooltipProps {
	/** Whether the tooltip is open */
	isOpen: boolean;
	/** Callback when open state changes */
	onOpenChange: (open: boolean) => void;
	/** Reference element to anchor the tooltip */
	itemRef: HTMLElement | null;
	/** Menu items to display */
	menuItems: NestedMenuItem[];
	/** Icon className */
	iconClassName?: string;
	/** Container className */
	className?: string;
	/** Called when mouse enters the tooltip */
	onMouseEnter?: () => void;
	/** Called when mouse leaves the tooltip */
	onMouseLeave?: () => void;
}

export function NestedMenuTooltip({
	isOpen,
	onOpenChange,
	itemRef,
	menuItems,
	iconClassName = "h-4 w-4",
	className,
	onMouseEnter,
	onMouseLeave,
}: NestedMenuTooltipProps) {
	if (!itemRef || !isOpen) return null;

	const rect = itemRef.getBoundingClientRect();

	return (
		<PopoverPrimitive.Root open={isOpen} onOpenChange={onOpenChange}>
			<PopoverPrimitive.Anchor
				style={{
					position: "fixed",
					left: rect.right,
					top: rect.top,
					width: 1,
					height: 1,
					pointerEvents: "none",
				}}
			/>
			<PopoverPrimitive.Portal>
				<PopoverPrimitive.Content
					side="right"
					align="start"
					sideOffset={10}
					className={cn(
						"z-50 min-w-[180px] overflow-hidden rounded-lg bg-popover p-1 text-popover-foreground shadow-lg animate-in fade-in-0 zoom-in-95",
						"data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
						className,
					)}
					onMouseEnter={onMouseEnter}
					onMouseLeave={onMouseLeave}
					onOpenAutoFocus={(e) => e.preventDefault()}
					onCloseAutoFocus={(e) => e.preventDefault()}
				>
					{menuItems.map((item) => {
						const Icon = item.icon;
						return (
							<button
								type="button"
								key={item.key}
								className={cn(
									"flex w-full items-center gap-2 rounded-md px-3 py-2 text-sm outline-none transition-colors",
									"hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground",
									item.variant === "danger" &&
										"text-destructive hover:bg-destructive/10 hover:text-destructive focus:bg-destructive/10",
									item.className,
								)}
								onClick={() => {
									item.onSelect?.();
									onOpenChange(false);
								}}
							>
								{Icon && (
									<span
										style={
											item.iconColor ? { color: item.iconColor } : undefined
										}
									>
										<Icon className={cn(iconClassName)} />
									</span>
								)}
								<span className="flex-1 text-left">{item.label}</span>
							</button>
						);
					})}
				</PopoverPrimitive.Content>
			</PopoverPrimitive.Portal>
		</PopoverPrimitive.Root>
	);
}

// ============================================================================
// NestedMenuItem Component
// ============================================================================

export interface NestedMenuItemComponentProps {
	/** Menu item data */
	item: NestedMenuItem;
	/** Icon className */
	iconClassName?: string;
	/** Whether to show arrow for submenu */
	showSubmenuArrow?: boolean;
	/** Arrow icon component */
	arrowIcon?: React.ComponentType<{ className?: string }>;
	/** Mouse enter handler (for submenu trigger) */
	onMouseEnter?: (e: React.MouseEvent<HTMLElement>) => void;
	/** Mouse leave handler */
	onMouseLeave?: () => void;
}

export function NestedMenuItemComponent({
	item,
	iconClassName = "h-6 w-6",
	showSubmenuArrow = true,
	arrowIcon: ArrowIcon,
	onMouseEnter,
	onMouseLeave,
}: NestedMenuItemComponentProps) {
	const Icon = item.icon;

	return (
		<button
			type="button"
			className={cn(
				"flex w-full items-center gap-2 rounded-lg px-3 py-2 text-sm outline-none transition-colors",
				"hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground",
				item.variant === "danger" &&
					"text-destructive hover:bg-destructive/10 hover:text-destructive focus:bg-destructive/10",
				item.className,
			)}
			onClick={() => !item.hasSubmenu && item.onSelect?.()}
			onMouseEnter={onMouseEnter}
			onMouseLeave={onMouseLeave}
		>
			{Icon && (
				<span style={item.iconColor ? { color: item.iconColor } : undefined}>
					<Icon className={cn(iconClassName)} />
				</span>
			)}
			<span className="flex-1 text-left">{item.label}</span>
			{item.hasSubmenu && showSubmenuArrow && ArrowIcon && (
				<ArrowIcon className="h-4 w-4 text-muted-foreground" />
			)}
		</button>
	);
}

// ============================================================================
// NestedMenuSection Component
// ============================================================================

export interface NestedMenuSectionComponentProps
	extends NestedMenuSectionProps {
	/** Icon className */
	iconClassName?: string;
	/** Arrow icon for submenu items */
	arrowIcon?: React.ComponentType<{ className?: string }>;
	/** Callback when item with submenu is hovered */
	onSubmenuHover?: (
		item: NestedMenuItem,
		e: React.MouseEvent<HTMLElement>,
	) => void;
	/** Callback when mouse leaves submenu trigger */
	onSubmenuLeave?: () => void;
}

export function NestedMenuSection({
	title,
	items,
	showDivider = false,
	iconClassName = "h-4 w-4",
	arrowIcon,
	onSubmenuHover,
	onSubmenuLeave,
}: NestedMenuSectionComponentProps) {
	return (
		<div className="py-1">
			{title && (
				<div className="px-2 py-1.5 text-xs font-medium text-muted-foreground">
					{title}
				</div>
			)}
			{items.map((item) => (
				<React.Fragment key={item.key}>
					<NestedMenuItemComponent
						item={item}
						iconClassName={iconClassName}
						arrowIcon={arrowIcon}
						onMouseEnter={
							item.hasSubmenu ? (e) => onSubmenuHover?.(item, e) : undefined
						}
						onMouseLeave={item.hasSubmenu ? onSubmenuLeave : undefined}
					/>
					{item.separator && <div className="my-1 h-px bg-border" />}
				</React.Fragment>
			))}
			{showDivider && <div className="my-1 h-px bg-border" />}
		</div>
	);
}

// ============================================================================
// NestedMenu Component (Full Menu with built-in submenu handling)
// ============================================================================

export interface NestedMenuProps {
	/** Menu sections */
	sections: NestedMenuSectionProps[];
	/** Trigger element */
	trigger: React.ReactNode;
	/** Icon className */
	iconClassName?: string;
	/** Arrow icon for submenu items */
	arrowIcon?: React.ComponentType<{ className?: string }>;
	/** Menu placement */
	side?: "top" | "right" | "bottom" | "left";
	/** Alignment relative to trigger */
	align?: "start" | "center" | "end";
	/** Offset from trigger */
	sideOffset?: number;
	/** Container className */
	className?: string;
	/** Controlled open state */
	open?: boolean;
	/** Callback when open state changes */
	onOpenChange?: (open: boolean) => void;
}

export function NestedMenu({
	sections,
	trigger,
	iconClassName = "h-4 w-4",
	arrowIcon,
	side = "right",
	align = "start",
	sideOffset = 8,
	className,
	open: controlledOpen,
	onOpenChange,
}: NestedMenuProps) {
	const [internalOpen, setInternalOpen] = useState(false);
	const isControlled = controlledOpen !== undefined;
	const open = isControlled ? controlledOpen : internalOpen;

	const handleOpenChange = useCallback(
		(newOpen: boolean) => {
			if (!isControlled) {
				setInternalOpen(newOpen);
			}
			onOpenChange?.(newOpen);
		},
		[isControlled, onOpenChange],
	);

	// Submenu state
	const [activeSubmenu, setActiveSubmenu] = useState<NestedMenuItem | null>(
		null,
	);
	const [submenuAnchor, setSubmenuAnchor] = useState<HTMLElement | null>(null);
	const submenuTimeoutRef = useRef<NodeJS.Timeout | null>(null);

	const handleSubmenuHover = useCallback(
		(item: NestedMenuItem, e: React.MouseEvent<HTMLElement>) => {
			if (submenuTimeoutRef.current) {
				clearTimeout(submenuTimeoutRef.current);
				submenuTimeoutRef.current = null;
			}
			setActiveSubmenu(item);
			setSubmenuAnchor(e.currentTarget);
		},
		[],
	);

	const handleSubmenuLeave = useCallback(() => {
		submenuTimeoutRef.current = setTimeout(() => {
			setActiveSubmenu(null);
			setSubmenuAnchor(null);
		}, 300);
	}, []);

	const handleSubmenuEnter = useCallback(() => {
		if (submenuTimeoutRef.current) {
			clearTimeout(submenuTimeoutRef.current);
			submenuTimeoutRef.current = null;
		}
	}, []);

	useEffect(() => {
		return () => {
			if (submenuTimeoutRef.current) {
				clearTimeout(submenuTimeoutRef.current);
			}
		};
	}, []);

	// Close submenu when main menu closes
	useEffect(() => {
		if (!open) {
			setActiveSubmenu(null);
			setSubmenuAnchor(null);
		}
	}, [open]);

	return (
		<>
			<PopoverPrimitive.Root open={open} onOpenChange={handleOpenChange}>
				<PopoverPrimitive.Trigger asChild>{trigger}</PopoverPrimitive.Trigger>
				<PopoverPrimitive.Portal>
					<PopoverPrimitive.Content
						side={side}
						align={align}
						sideOffset={sideOffset}
						className={cn(
							"z-50 min-w-[200px] overflow-hidden rounded-xl px-2 py-1 bg-popover text-popover-foreground shadow-lg animate-in fade-in-0 zoom-in-95",
							"data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
							className,
						)}
						onOpenAutoFocus={(e) => e.preventDefault()}
						onCloseAutoFocus={(e) => e.preventDefault()}
						onInteractOutside={(e) => {
							// Prevent closing when interacting with submenu
							const target = e.target as HTMLElement;
							if (target?.closest("[data-radix-popper-content-wrapper]")) {
								e.preventDefault();
							}
						}}
					>
						{sections.map((section, index) => (
							<NestedMenuSection
								key={section.title || `section-${index}`}
								{...section}
								iconClassName={iconClassName}
								arrowIcon={arrowIcon}
								onSubmenuHover={handleSubmenuHover}
								onSubmenuLeave={handleSubmenuLeave}
							/>
						))}
					</PopoverPrimitive.Content>
				</PopoverPrimitive.Portal>
			</PopoverPrimitive.Root>

			{/* Submenu */}
			{activeSubmenu?.submenuItems && (
				<NestedMenuTooltip
					isOpen={!!activeSubmenu}
					onOpenChange={(isOpen) => {
						if (!isOpen) {
							setActiveSubmenu(null);
							setSubmenuAnchor(null);
						}
					}}
					itemRef={submenuAnchor}
					menuItems={activeSubmenu.submenuItems}
					iconClassName={iconClassName}
					onMouseEnter={handleSubmenuEnter}
					onMouseLeave={handleSubmenuLeave}
				/>
			)}
		</>
	);
}

export default NestedMenu;

Update the import paths to match your project setup.

Similar screens