React Router v4 and nested routes: index navlink always remain active

Viewed 3922

Currently i have this routing structure:

//Main.js:

 <Router>
    <Switch>
        <Route exact path='/' component={AuthApp}/>
        <Route path='/app' component={ContentApp}/>
    </Switch>
</Router>

I need some inner navigation inside of my ContentApp:

//ContentApp:
<Route exact path={`${match.url}/`} component={Content}/>
<Route exact path={`${match.url}/something`} component={Something}/>
<Route exact path={`${match.url}/else`} component={Else}/>
<Route exact path={`${match.url}/blahblah`} component={BlahBlah}/>

And some navigation ofc:

//Header.js
<NavLink exact to='/app' >Dashboard</NavLink>
<NavLink to='/app/something' >Something</NavLink>
<NavLink to='/app/else' >Else</NavLink>
<NavLink to='/app/blahblah' >BlahBlah</NavLink>

So the thing is: its working just fine, however the first link always remains active. Can anyone suggest how can i solve this problem? Thanks

2 Answers

In React Router V6 Use end= {true}, Just like the example in Below,

<NavLink
              className={({ isActive }) =>
                isActive ? "active nav-link" : "nav-link"
              }
              to="/admin/new"
            >
              Add New
            </NavLink>
          </li>
          <li class="nav-item">
            <NavLink
              className={({ isActive }) =>
                isActive ? "active nav-link" : "nav-link"
              }
              to="/admin"
              end={true}
            >
              Manage
            </NavLink>

In This Example, I use Two routes /admin and /admin/new to detect /admin/new path I added end= {true}.

Related