Learn how to style an active link based on the current route in Next.js to improve user experience and navigation.
This article will guide you through implementing active links in Next.js, enhancing navigation by visually highlighting the current page. While Next.js lacks a built-in solution, we'll explore effective methods using JavaScript and CSS. The first approach involves the useRouter hook and CSS classes to dynamically style active links. We'll import necessary components, define CSS classes for active and inactive states, and create a NavLink component to apply styling based on the current route. The second method utilizes a custom ActiveLink component with the next-active-link package, simplifying active link management and offering seamless integration with UI libraries like Chakra UI. We'll cover installation, component creation, and usage. Additional considerations include styling customization, mapping links for dynamic rendering, and exploring advanced routing libraries for complex scenarios. By following these steps, you'll effectively implement active link styling in your Next.js applications, improving user experience and navigation clarity.
While Next.js doesn't have a built-in solution for active link styling, there are several effective methods to achieve this. Here's a step-by-step guide using JavaScript and incorporating insights from the provided resources:
Method 1: Using the useRouter Hook and CSS Classes
import Link from 'next/link';
import { useRouter } from 'next/router';Create CSS classes for both active and inactive link states. For example:
.nav-link {
color: #333;
text-decoration: none;
}
.nav-link.active {
color: #0070f3;
font-weight: bold;
}function NavLink({ href, children }) {
const router = useRouter();
const isActive = router.asPath === href;
return (
<Link href={href}>
<a className={`nav-link ${isActive ? 'active' : ''}`}>{children}</a>
</Link>
);
}NavLink Component:<NavLink href="/">Home</NavLink>
<NavLink href="/about">About</NavLink>Explanation:
Link for creating links and useRouter to access the current route information.NavLink component checks if the current route (router.asPath) matches the link's href and applies the active class accordingly.NavLink component to create our navigation links.Method 2: Using a Custom ActiveLink Component (with Chakra UI Example)
next-active-link Package:npm install next-active-linkActiveLink Component:import ActiveLink from 'next-active-link';
import { Link } from '@chakra-ui/react';
function CustomActiveLink({ href, children, ...props }) {
return (
<ActiveLink href={href} activeClassName="active" passHref>
<Link {...props}>{children}</Link>
</ActiveLink>
);
}CustomActiveLink Component:<CustomActiveLink href="/">Home</CustomActiveLink>
<CustomActiveLink href="/about">About</CustomActiveLink>Explanation:
next-active-link package, which provides a convenient way to manage active links.ActiveLink component that wraps the Chakra UI Link component and uses the activeClassName prop from next-active-link.Additional Considerations:
NavLink or CustomActiveLink components for each item.react-router-dom for more advanced routing and active link management.By following these steps and adapting them to your specific needs, you can effectively implement active link styling in your Next.js applications.
This code provides two methods for implementing active links in Next.js applications. The first method utilizes the useRouter hook and CSS classes to determine and style active links. The second method employs the next-active-link package, showcasing its integration with Chakra UI for styling active links. Both methods offer solutions for visually indicating the current page to users, enhancing navigation experience.
Here's the JavaScript code for the two methods described in the article, along with explanations:
Method 1: Using useRouter and CSS Classes
import Link from 'next/link';
import { useRouter } from 'next/router';
// Define your CSS classes for active and inactive links
// (you can put this in a separate CSS file)
const navLinkStyles = {
base: 'text-blue-500 hover:text-blue-700',
active: 'font-bold underline',
};
function NavLink({ href, children }) {
const router = useRouter();
const isActive = router.asPath === href;
// Combine base styles with active styles if the link is active
const className = `${navLinkStyles.base} ${isActive ? navLinkStyles.active : ''}`;
return (
<Link href={href}>
<a className={className}>{children}</a>
</Link>
);
}
// Example usage in your component
<nav>
<NavLink href="/">Home</NavLink>
<NavLink href="/about">About</NavLink>
</nav>Explanation:
Link for creating Next.js links and useRouter to access the current route information.NavLink component takes href and children props for the link's destination and content.useRouter to get the current route (router.asPath).href to determine if the link is active.Link with the calculated className.Method 2: Using next-active-link (with Chakra UI Example)
import ActiveLink from 'next-active-link';
import { Link } from '@chakra-ui/react';
function CustomActiveLink({ href, children, ...props }) {
return (
<ActiveLink href={href} activeClassName="active" passHref>
<Link {...props}>{children}</Link>
</ActiveLink>
);
}
// Example usage (assuming you have Chakra UI set up)
<nav>
<CustomActiveLink href="/">
<Text>Home</Text>
</CustomActiveLink>
<CustomActiveLink href="/about">
<Text>About</Text>
</CustomActiveLink>
</nav>Explanation:
npm install next-active-link.href, children, and any additional props to pass to the Chakra UI Link component.ActiveLink from next-active-link and provides the href and activeClassName (which should match your CSS class for active links).passHref prop ensures that the href is passed to the underlying a tag for proper link behavior.Link with the provided children and props.Choosing a Method:
next-active-link./blog and another to /blog/post-1, you might not want the /blog link to be active when you're on /blog/post-1. You can achieve this by using the exact prop with next-active-link or by implementing your own logic to compare paths more precisely.href or using a library like path-to-regexp for more complex matching.pages/blog/[slug].js), you'll need to make sure your active link logic can handle the dynamic segments. This might involve extracting the slug from the current route and comparing it to the link's href.By considering these additional notes and exploring alternative techniques, you can implement active links in your Next.js applications effectively and ensure a seamless user experience.
| Method | Description | Key Steps | Benefits | Drawbacks |
|---|---|---|---|---|
Using useRouter Hook and CSS Classes |
Manually manage active state with JavaScript and CSS. | 1. Import Link and useRouter. 2. Define CSS classes for active/inactive states. 3. Create NavLink component to apply classes based on route. 4. Use NavLink for navigation. |
Simple and flexible. No external dependencies. | Requires more code and manual state management. |
Using next-active-link Package |
Leverage a dedicated package for active link management. | 1. Install next-active-link. 2. Create custom component with ActiveLink and desired UI library (e.g., Chakra UI). 3. Use custom component for navigation. |
Easier to implement and maintain. Integrates with UI libraries. | Adds an external dependency. |
Implementing active links in your Next.js applications is crucial for providing a clear and intuitive navigation experience for your users. While Next.js doesn't offer a built-in solution, the methods outlined in this guide empower you to achieve this functionality effectively. Whether you choose the flexibility of the useRouter hook and CSS classes or the convenience of the next-active-link package, you can tailor the approach to your specific project requirements and preferences.
Remember to consider additional factors such as exact path matching, nested routes, dynamic routing, performance optimization, accessibility, server-side rendering, and thorough testing to ensure a robust and user-friendly implementation. By carefully addressing these aspects, you can create a navigation system that guides users seamlessly through your application, enhancing their overall experience.
Implementing ActiveLink in Next.js and Chakra - DEV Community | How to implement an Navlink for Chakra and Next.js the easy
How to create Active NavLink in Nextjs | by Mike Gajdos | Medium | How does one target active Link in Nextjs like the way we do it in React-Router? While I was building my blog I wanted to provide an…
Next.js version of activeClassName support. · GitHub | Next.js version of activeClassName support. GitHub Gist: instantly share code, notes, and snippets.
API Reference | Vue Router | The official router for Vue.js ... In addition, the link automatically gets an active CSS class when the target route is active. ... next(err) inside a route guard ...
Using the router to detect the active link in Next.js | How to using the Next.js Router to detect the active link and assign a class to it, so we can style it with CSS