While I was learning about clsx library for conditional CSS class composition, I tried to experiment with it by implementing active links on navbar. I have created this rough nav-link component. The code works fine with pathname === link.href. When I change link.href to let's say '/dashboard' or '/dashboard/invoice', all the links get highlighted including the given link
Initial Code:
'use client';
import clsx from 'clsx';
import Link from 'next/link';
import {usePathname} from 'next/navigation'
const links = [
{ name: 'Home',
href: '/dashboard',
icon: HomeIcon },
{
name: 'Invoices',
href: '/dashboard/invoices',
icon: DocumentDuplicateIcon,
},
{ name: 'Customers',
href: '/dashboard/customers',
icon: UserGroupIcon },
];
export default function NavLinks() {
const pathname = usePathname()
return (
<>
{links.map((link) => {
const LinkIcon = link.icon;
console.log(link.href);
return (
<Link
key={link.name}
href={link.href}
className={clsx('flex h-[48px] grow items-center justify-center gap-2 rounded-md bg-gray-50 p-3 text-sm font-medium hover:bg-sky-100 hover:text-blue-600 md:flex-none md:justify-start md:p-2 md:px-3',
{'bg-red-200 text-red-600': pathname === link.href}
)}
>
<LinkIcon className="w-6" />
<p className="hidden md:block">{link.name}</p>
</Link>
);
})}
</>
);
}
Final Code :
'use client';
import clsx from 'clsx';
import Link from 'next/link';
import {usePathname} from 'next/navigation'
const links = [
{ name: 'Home',
href: '/dashboard',
icon: HomeIcon },
{
name: 'Invoices',
href: '/dashboard/invoices',
icon: DocumentDuplicateIcon,
},
{ name: 'Customers',
href: '/dashboard/customers',
icon: UserGroupIcon },
];
export default function NavLinks() {
const pathname = usePathname()
return (
<>
{links.map((link) => {
const LinkIcon = link.icon;
return (
<Link
key={link.name}
href={link.href}
className={clsx('flex h-[48px] grow items-center justify-center gap-2 rounded-md bg-gray-50 p-3 text-sm font-medium hover:bg-sky-100 hover:text-blue-600 md:flex-none md:justify-start md:p-2 md:px-3',
{'bg-red-200 text-red-600': pathname === '/dashboard'}
)}
>
<LinkIcon className="w-6" />
<p className="hidden md:block">{link.name}</p>
</Link>
);
})}
</>
);
}