Amir Shahbabaie
Amir Shahbabaie

Reputation: 1412

NavLink needs to be active on two routes React-Router

I have a few NavLinks like these:

<NavLink to="/dashboard" >
    <i className="icon icon-home-icon-01"></i>
</NavLink>
<NavLink to="/searchplatform" >
    <i className="icon icon-search-icon-01"></i>
</NavLink>
<NavLink to="/boxes" >
    <i className="icon icon-line-state-01""></i>
</NavLink>

I want the second Navlink to be active on two routes, /searchplatform and /search/results.

And, no I dont want to have two different NavLinks obviously!

Thanks indeed

Upvotes: 5

Views: 3531

Answers (2)

sledgeweight
sledgeweight

Reputation: 8095

I just used a ternary for the to=<path> inverting a matched location to a specific event page and the activeClassName for react router v5. This keeps the Navlink linkable and active for both /event/<eventid> and /events

<NavLink
    to={!location.pathname.includes('/event/') ? '/events' : '/event'}
    activeClassName='link__header--active'
    ...etc...
/>

Upvotes: 0

Ganapati V S
Ganapati V S

Reputation: 1661

You should use isActive function prop on NavLink. This you can return true from this function for the routes you want.

Read more about isActive function prop here.

Upvotes: 5

Related Questions