Categories
React Answers

How to add an active class to a Link from React Router?

Spread the love

Sometimes, we want to add an active class to a Link from React Router.

In this article, we’ll look at how to add an active class to a Link from React Router.

How to add an active class to a Link from React Router?

To add an active class to a Link from React Router, we can use the NavLink component with the activeClassName prop.

For instance, we write

<NavLink to="/hello" activeClassName="active">
  Hello
</NavLink>

to add a NavLink component with the to prop set to the destination URL.

And the activeClassName set to the CSS class that we apply when we reach the destination URL.

Conclusion

To add an active class to a Link from React Router, we can use the NavLink component with the activeClassName prop.

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 *