Categories
React Answers

How to add active link with React-Router v6?

Spread the love

Sometimes, we want to add active link with React-Router v6.

In this article, we’ll look at how to add active link with React-Router v6.

How to add active link with React-Router v6?

To add active link with React-Router v6, we set the className prop of the NavLink component to a function that returns the class name.

For instance, we write

<NavLink
  to="users"
  className={({ isActive }) =>
    isActive ? "bg-green-500 font-bold" : "bg-red-500 font-thin"
  }
>
  Users
</NavLink>

to add a NavLink that goes to the users route.

We set the className prop to a function that gets the isActive property from the parameter.

Then we return the class name value according to the value of isActive in the function.

Conclusion

To add active link with React-Router v6, we set the className prop of the NavLink component to a function that returns the class name.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *