How to target the active Link in Next.js (next 13)
const Sidebar = () => {
const link = [
{
label: ' Home',
path: '/',
},
{
label: ' About',
path: '/about',
}
]
return (
<div>
{sidebarLink.map((link, index) =>
<Link
key={link.index}
href={link.path}>
</Link>
)}
</div>
)
}
export default Sidebar
I tried everything to no avail
Edit. Please refer to the answer below as it's more accurate. It uses what at the time of my answer wasn't available and is next js api:
https://stackoverflow.com/a/76863393
Not really ideal but this is what I am doing.
"use client"; // if you are planing to use it in the component which is not marker with use client directive this is a must
import Link, { LinkProps } from "next/link";
import { usePathname } from "next/navigation"; // usePathname is a hook now imported from navigation
const ActiveLink = ({
children,
...rest
}: { children: React.ReactNode } & LinkProps) => {
const { href } = rest;
const pathName = usePathname();
const isActive = pathName === href;
return (
// you get a global isActive class name, it is better than
// nothing, but it means you do not have scoping ability in
// certain cases
<Link {...rest} className={isActive ? "active" : ""}>
{children}
</Link>
);
};
export default ActiveLink;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With