Ben Botvinick
Ben Botvinick

Reputation: 3325

React Router: NavLink based on hash

I'm trying to create a navigation bar that displays the active link based on the page's hash using React Router's NavLink component. Here's what I have:

<NavLink to="#home">Home</NavLink>
<NavLink to="#about">About</NavLink>

Both of these links have the active class, no matter what the hash is. How can I make the link display as active based on the current hash?

Upvotes: 1

Views: 2421

Answers (1)

Iskren Lalov
Iskren Lalov

Reputation: 39

You can do the following:

<NavLink
  to='/#contact'
  isActive={() => {
    return window.location.hash === '#contact';
  }}>
  Contact
</NavLink>

isActive: func

A function to add extra logic for determining whether the link is active. This should be used if you want to do more than verify that the link’s pathname matches the current URL’s pathname.

Upvotes: 1

Related Questions