乐闻世界logo
搜索文章和话题

How to target active link when the route is active in next js

1个答案

1

In Next.js, when you want to change link styles upon route matching, you can leverage the Link component and useRouter hook provided by Next.js to achieve this. Here's a step-by-step guide with code examples:

  1. Import necessary modules - Import the Link component from next/link and the useRouter hook from next/router.
  2. Use useRouter - Inside your component, use the useRouter hook to obtain the current route object.
  3. Compare routes - Use the pathname property of the route object to determine if the current route matches the link's target route.
  4. Set styles - Dynamically apply different style classes or style objects to your link element based on whether the route matches.

Here's a simplified code example demonstrating how to implement this:

jsx
import Link from 'next/link'; import { useRouter } from 'next/router'; export default function NavLink({ href, children }) { // Use the useRouter hook to get current route information const router = useRouter(); // Check if this link is the current route; if so, apply a special style class const isActive = router.pathname === href; // Determine styles based on active state const linkStyle = { fontWeight: isActive ? 'bold' : 'normal', color: isActive ? 'green' : 'blue', }; return ( <Link href={href}> <a style={linkStyle}>{children}</a> </Link> ); }

This NavLink component can be used as follows:

jsx
function NavigationBar() { return ( <nav> <NavLink href="/">Home</NavLink> <NavLink href="/about">About</NavLink> <NavLink href="/contact">Contact</NavLink> </nav> ); }

In this example, when a user navigates to a route matching the href attribute of a NavLink, the link style becomes bold and green. If it doesn't match, the link style will be normal font and blue. This makes it intuitive for users to identify their current page.

This is a straightforward approach to styling links. You can also combine style classes with element classes to enhance the complexity and flexibility of your styles.

2024年6月29日 12:07 回复

你的答案