#add active `className` to my current route
1 messages · Page 1 of 1 (latest)
You can use the usePathname() function from Next.js to determine if a link is active. This function allows you to check if the current pathname matches the href of the link. If it does, you can add an 'active' class to the link.
Here's how you can modify your code to add an 'active' class to the current route:
import { usePathname } from 'next/navigation'
import Link from 'next/link'
export function NavigationMenu({ routes, styles }) {
const pathname = usePathname()
return (
<nav>
<ul className={styles.menu}>
{routes.map(({ route, href }) => (
<li key={href} className={styles.item}>
<Link className={`link ${pathname === href ? 'active' : ''}`} href={href}>
{route}
</Link>
</li>
))}
</ul>
</nav>
)
}
In this code, usePathname() is used to get the current pathname. Then, for each link, we check if the pathname is equal to the href of the link. If it is, we add the 'active' class to the link.
Please note that you need to define the 'active' class in your CSS to style the active link as desired.
This information is based on the Next.js documentation on Checking Active Links (https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating#checking-active-links).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@undone yoke kapa.ai is still learning and improving, please let us know how it did by reacting below
Let me check the knowledge base for you. One moment! :books:
The error message you're seeing is indicating that you're trying to use the usePathname hook from Next.js in a Server Component. This hook is only meant to be used in Client Components.
In Next.js, there are two types of components: Server Components and Client Components. Server Components are rendered on the server and do not have access to any client-side features like hooks or event handlers. Client Components, on the other hand, are rendered on the client and can use all React features, including hooks.
To fix this error, you need to mark the component that's using usePathname as a Client Component. You can do this by adding the use client directive at the top of your component file. Here's an example:
"use client";
import { usePathname } from 'next/navigation'
// rest of your component code
This will tell Next.js that this component should be treated as a Client Component and it will allow you to use usePathname and other client-side features.