CodeNewbie Community 🌱

Cover image for How to add styling to an active link in NextJS
𝕁𝕦𝕝𝕚𝕒 👩🏻‍💻
𝕁𝕦𝕝𝕚𝕒 👩🏻‍💻

Posted on • Edited on

How to add styling to an active link in NextJS

This article was originally published on dev.to

For my latest project, I wanted to change the background color of the active navigation link in the <Header> when being clicked. When working with <Link> in React (using React-Router) in the past, I had the possibility to add an activeClassName to the <Link> to change the style when being active. But this built-in <Link> is not available in NextJS. Let me show you the differences and how you can add an active class to a Link in NextJS.


Table Of Contents

  1. React's activeClassName
  2. Create an active link in NextJS

React's activeClassName

This special version of the <Link> tag is called <NavLink> and adds styling attributes to the rendered element when it matches the current URL. There are two different ways to add styling.

  • activeClassName: string

The class is given to the element when it is active by writing:

<NavLink to="/about" activeClassName="active">
  About
</NavLink>
Enter fullscreen mode Exit fullscreen mode
  • activeStyle: object

The styles is applied to the element when it is active by writing:

important: use double curly brackets instead of single ones in activeStyle*

<NavLink to="/about" activeStyle={fontWeight: "bold"}>
  About
</NavLink>
Enter fullscreen mode Exit fullscreen mode

Create an active link in NextJS

The default <Link> component from NextJS doesn't allow to distinguish between active and non-active links. In NextJS, you can use the built-in router to detect an active link.

I am using the useRouter hook inside my "Header function component" and created a ternary operator to check if the <Link> to style matches the currently displayed route.

Here's the code:

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

export const Header = () => {
  const router = useRouter();

  return (
    <header>
      <Link href="/">
        <a className={router.pathname == "/" ? "active" : ""}>
           Home
        </a>
      </Link>
    </header>
  )
}
Enter fullscreen mode Exit fullscreen mode

For more information on next/router check out the documentation.

*) When I try to save it with double curly brackets an error message appears.


Thank you

Thanks for your reading and time. I really appreciate it!

Top comments (0)