reactjsreact-routerreact-router-dom

React Router Dom v6 shows active for index as well as other subroutes


<Route path='/dashboard' element={<Navbar />}>
     <Route index element={<Home />} />
     <Route path='profile' element={<Profile />} />
     <Route path='wallets' element={<Wallet />} />
     <Route path='users' element={<Users />} />
</Route>

Here's my code and what basically happens is in my Navbar I got the active page link marked blue So when I'm on /dashboard it shows Home in blue But when I'm on /dashboard/profile it shows both home and profile in blue

<li>
    <NavLink to=''>
      {({ isActive }) =>
         isActive ? (
               <text style={{color: blue}}>Home</text>
         ) : (                      
               <text>Home</text>
         )
      }
    </NavLink>
</li>
<li>
    <NavLink to='profile'>
    {({ isActive }) =>
         isActive ? (
               <text style={{color: blue}}>Profile</text>
         ) : (                      
               <text>Profile</text>
         )
    }
    </NavLink>
</li>
                      

Solution

  • You can specify the end prop on the "root"-level link to the "/dashboard" path.

    NavLink

    If the end prop is used, it will ensure this component isn't matched as "active" when its descendant paths are matched.

    <NavLink to='' end>
      {({ isActive }) =>
         isActive ? (
               <text style={{color: blue}}>Home</text>
         ) : (                      
               <text>Home</text>
         )
      }
    </NavLink>
    

    Edit react-router-dom-v6-shows-active-for-index-as-well-as-other-subroutes