DEV Community

loading...
Cover image for How to add styling to an active link in NextJS

How to add styling to an active link in NextJS

yuridevat profile image Julia Undeutsch Updated on ・2 min read

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` 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:

Alt Text

activeStyle: object

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

Create an active link in NextJS

The default `´ 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:

Alt Text

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


Thank you

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

Discussion (2)

Collapse
jsingle345 profile image
Joshua Singleton

This helped me out tremendously. Helped me out so much that I created an account just to say thank you!

Collapse
yuridevat profile image
Julia Undeutsch Author

Thank you so much for your kind words :) Glad it helped!

Forem Open with the Forem app