From c937f3290bc2ea5938f6fd9616b6f8acc38ed88c Mon Sep 17 00:00:00 2001 From: David Moore Date: Thu, 17 Oct 2024 16:08:25 +1100 Subject: [PATCH] ensure deeply nested collapsible nav items are active on init --- src/components/nav/CollapsibleNavItem.tsx | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/components/nav/CollapsibleNavItem.tsx b/src/components/nav/CollapsibleNavItem.tsx index 6302df327..de19005d5 100644 --- a/src/components/nav/CollapsibleNavItem.tsx +++ b/src/components/nav/CollapsibleNavItem.tsx @@ -7,13 +7,27 @@ import { cn } from '@/lib/utils' import { NavLink } from './NavLink' import { usePathname } from 'next/navigation' import { Button } from '../ui/button' -import { NavGroup } from '@/config/types' +import { NavEntry, NavGroup } from '@/config/types' interface Props { group: NavGroup className?: string } +const checkIfActive = (items: NavEntry[], pathname: string): boolean => { + return items.some((link) => { + if ('href' in link && link.href === pathname) { + return true + } + + if ('items' in link && Array.isArray(link.items)) { + return checkIfActive(link.items, pathname) + } + + return false + }) +} + const CollapsibleNavItem: React.FC = ({ group, className }) => { const pathname = usePathname() @@ -22,9 +36,8 @@ const CollapsibleNavItem: React.FC = ({ group, className }) => { const { title, items, icon: Icon } = group - const isActive = items.some( - (link) => 'href' in link && link.href === pathname, - ) + const isActive = checkIfActive(items, pathname) + const [isOpen, setIsOpen] = React.useState(isActive) return (