DEV Community

Cover image for Effortlessly Highlight Active Links in Your Next.js Application with useActiveRouter Hook
Rishabh
Rishabh

Posted on • Updated on

Effortlessly Highlight Active Links in Your Next.js Application with useActiveRouter Hook

Highlighting the active link in a Next.js application with multiple pages and navigation links can be a tedious and error-prone task. However, the useActiveRouter hook from the active-link-nextjs package can simplify this process. By defining a configuration object with the active class name and using the registerRoute function returned by the hook with the Link component, the active link can be easily highlighted.

What is useActiveRouter?

useActiveRouter is a nextjs hook that can be imported from active-link-nextjs package. To install this package you can do

npm install active-link-nextjs
This hook takes a config object as parameter where you can define the name of active class to be auto applied to active link.
it returns an object containing href and className properties.

import { useActiveRouter } from 'active-link-nextjs';
import Link from 'next/link';

const config = { activeClass: 'active' };

const MyComponent: React.FC = () => {
    const { registerRoute } = useActiveRouter(config);

    return (
        <nav>
        <Link {registerRoute([''])}>Home</Link>
        <Link {registerRoute(['about'])}>About</Link>
        <Link {registerRoute(['blog'])}>Blog</Link>
        </nav>
    );
};
Enter fullscreen mode Exit fullscreen mode

In this example, we first import the useActiveRouter hook from the active-link-nextjs package and the Link component from the next/link package. We then define a configuration object with an activeClass property set to 'active'. This is the class name that will be added to the active link's a tag.

We then call useActiveRouter with the configuration object, which returns the registerRoute function. We can then use this function to generate the href and className properties for each navigation link.

Instead of using an a tag, we wrap the Link component around the result of the registerRoute function. This ensures that the link is pre-fetched by Next.js, which can improve the app's performance.

Why use useActiveRouter and Link?

Using useActiveRouter and Link can simplify the process of adding an active class to the active link in a Next.js app. Instead of manually checking the current route and adding the class name, we can use the registerRoute function to handle this for us. This can save us time and reduce the chance of errors, especially if our app has many pages and nested routes.

Conclusion

If you’re building a Next.js app with multiple pages and navigation links, useActiveRouter and Link can help simplify the process of highlighting the active link. By using the registerRoute function and Link component

Contributions and suggestions are welcome Github

Top comments (0)