Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React router V6 <NavLink to="/" /> is always active

I have defined a few routes:

const MainRoutes = {
  path: "/",
  element: <MainLayout />,
  children: [
    {
      index: true,
      element: <DashboardDefault />,
    },
    {
      path: "werknemers",
      element: <Werknemers />
    },
    {
      path: "verzuimdossiers",
      element: <Verzuimdossiers />
    }
  ],
};

My <MainLayout /> contains the Sidebar, Header and Outlet. In my Sidebar, I have a few <NavLinks/> like so:

<NavLink exact to="/" className={({ isActive })=> (isActive ? `active ${LINK_CLASSES}` : `inactive ${LINK_CLASSES}`)}>
  <span>Dashboard</span>
</NavLink>
<NavLink to="werknemers" className={({ isActive })=> (isActive ? `active ${LINK_CLASSES}` : `inactive
  ${LINK_CLASSES}`)}>
  <span>Werknemers</span>
</NavLink>
<NavLink to="verzuimdossiers" className={({ isActive })=> (isActive ? `active ${LINK_CLASSES}` : `inactive
  ${LINK_CLASSES}`)}>
  <span>Verzuimdossiers</span>
</NavLink>

However, my <NavLink/> for the root "/" is always active. The other 2 work just fine. If I am on "/werknemers" I do not want the Dashboard route to be also active…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What am I missing here?

>Solution :

In React Router you were using exact property to exactly match the URL in the browser. However, this only works in V5. In V6, they have changed it to end instead. So you have to do something like this:

<NavLink end to="/messages">Link</NavLink>

Reference documentation upgrading from V5 to V6: https://reactrouter.com/en/6.4.1/upgrading/v5#rename-navlink-exact-to-navlink-end

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading