Back To Snippets

ActiveLink

Next.js 13 Link Abstraction for Active Link Styling.

active-link.tsx

active-link.tsx

'use client'; import { AnchorHTMLAttributes, forwardRef } from 'react'; import Link, { LinkProps } from 'next/link'; import { usePathname } from 'next/navigation'; import { twMerge } from 'tailwind-merge'; type ActiveLinkProps = LinkProps & AnchorHTMLAttributes<HTMLAnchorElement> & { activeClassName?: string; }; export const ActiveLink = forwardRef<HTMLAnchorElement, ActiveLinkProps>( ({ className, activeClassName, href, ...props }, ref) => { const pathname = usePathname(); const isActive = pathname === href; return ( <Link ref={ref} href={href} className={twMerge(className, isActive && activeClassName)} {...props} /> ); }, ); ActiveLink.displayName = 'ActiveLink';

Usage

src/app/page.tsx

src/app/page.tsx

<ActiveLink href="/snippets" className="text-blue-500 hover:text-blue-500/70" activeClassName="text-orange-500 hover:text-orange-500/70" > Snippets </ActiveLink>