Next.js: How to Highlight Currently Active Link

Last updated on May 21, 2022 A Goodman Loading... Post a comment

In a web app, giving an active link a special CSS style will enhance the user experience and makes it easier for them to navigate and know where they are.

This article shows you how to highlight a currently active link in Next.js by making use of the useRouter hook. Without any further ado, let’s get started.

Overview

In order to determine whether a link is active or not, we will get information about the current route and then compare it to the href of the link, like this:

{/* Get the current route */}
const router = useRouter();
const currentRoute = router.pathname;

{/* Render Link */}
<Link href="/some-path">
    <a className={currentRoute === "/some-path" 
       ? "active" 
       : "non-active"}>
         About
     </a>
</Link>

For more clarity, see the full example below.

Complete Example

App Preview

The sample project we are going to build consists of three pages (routes) as follows:

  • /: Home
  • /about: About
  • /contact: Contact

You can navigate between pages by using the pink navigation bar. The non-active links will be white and the active link will be dark with an orange background color.

Here’s how it works:

The Code

1. Create a new Next.js project:

npx create-next-app kindacode-example

You can choose another name if you like.

2. In the root directory of the project, add a new folder named components. Inside this folder, create a new file called nav-bar.js. This file is where we implement the NavBar component that will be used on all three pages:

// components/nav-bar.js

import Link from 'next/link'
import { useRouter } from 'next/router'

// Navigation Bar
// This component will be used on all pages
const NavBar = () => {
    const router = useRouter();
    const currentRoute = router.pathname;

    return (
        <nav>
            <Link href="/">
                <a className={currentRoute === "/" ? "active" : "non-active"}>Home</a>
            </Link>

            <Link href="/about">
                <a className={currentRoute === "/about" ? "active" : "non-active"}>About</a>
            </Link>

            <Link href="/contact">
                <a className={currentRoute === "/contact" ? "active" : "non-active"}>Contact</a>
            </Link>

            {/* Style the nav bar */}
            {/* This example uses Styled JSX but you can use other approach if you like */}
            <style jsx>{`
                nav {
                    height: 56px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    background: #e91e63;
                    box-shadow: 0 5px 10px #ccc;
                  }
                  
                  /* Basic styles for nav links */
                  nav a {
                    display: flex;
                    align-items: center;
                    padding-left: 30px;
                    padding-right: 30px;
                    height: 100%;
                    text-decoration: none;
                  }
                  
                  /* Specific styles for non-active links */
                  .non-active {
                    color: white;
                  }
                  
                  /* Specific styles for active links */
                  .active {
                    color: black;
                    background: orange;
                  }
            `}</style>
        </nav>
    );
};

export default NavBar;

3. Replace all of the default code in pages/index.js with the following:

// pages/index.js
import NavBar from '../components/nav-bar'

export default function Home(props) {

  return (
    <>
      <NavBar />

      <div style={{padding: 30}}>
        <h1>Home Page</h1>
        <p>Welcome to KindaCode.com</p>
      </div>
    </>
  )
}

4. In the pages folder, create a new file named about.js then add the following code to it:

// pages/about.js
import NavBar from '../components/nav-bar'

export default function About(props) {

  return (
    <>
      <NavBar />

      <div style={{padding: 30}}>
        <h1>About Page</h1>
        <p>This is the About page</p>
      </div>
    </>
  )
}

5. In the pages folder, add a new file called contact.js. Here’s the code for it:

// pages/contact.js
import NavBar from '../components/nav-bar'

export default function Contact(props) {

  return (
    <>
      <NavBar />

      <div style={{padding: 30}}>
        <h1>Contact Page</h1>
        <p>Contact me at [email protected]</p>
      </div>
    </>
  )
}

Everything is done. Here’s the final file structure of our project:

Let’s run it by executing the following command:

npm run dev

Go to http://localhost:3000 to see the result.

Conclusion

You’ve learned how to highlight active links in Next.js. You can improve on the code in the example and make it even better if you want. Keeping yourself on track and explore more new things by taking a look at the following articles:

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles