SlothOverlord
SlothOverlord

Reputation: 2037

react-router-dom v6 NavLink is always active

I followed Upgrading from v5 guide and I cannot get the NavLink component to work correctly.

https://reactrouter.com/docs/en/v6/upgrading/v5#upgrading-from-v5

v6 Navlinks:

    <NavLink
          className={(isActive) =>
            cx(isActive ? classes.linkActive : classes.link)
          }
          to="/seafarers"
          end
        >
          Seafarers
        </NavLink>
        <NavLink
          className={(isActive) =>
            cx(isActive ? classes.linkActive : classes.link)
          }
          end
          to="/"
        >
          Planning
        </NavLink>

Routes

    <BrowserRouter>
      <Routes>
        <Route path="/" element={<LoginScreen />} />
        <Route path="login" element={<LoginScreen />} />
        <Route path="forgot-password" element={<ForgotPasswordScreen />} />
        <Route path="seafarers" element={<SeafarersScreen />} />
      </Routes>
    </BrowserRouter>

Both "/" and "/seafarers" have active class

Note: NavLink elements are located in SeafarersScreen screen

How can I correct this issue?

Upvotes: 10

Views: 13192

Answers (4)

easyScript
easyScript

Reputation: 633

Add end prop on parent route. This work for react-router-dom: 6.4.4.

    <NavLink
        to="/"
        end
        className={({ isActive }) =>`nav-link ${isActive && 'active'}`}>
      Notes
    </NavLink>

From react-router documentation, here is the link: https://reactrouter.com/en/main/components/nav-link

Upvotes: 5

asad minhas
asad minhas

Reputation: 281

<NavLink
  to="/"
  style={({ isActive }) => ({ color: isActive ? "green" : "blue" })}
  className={yourClasses}
>
  Profile
</NavLink>

Upvotes: 1

SlothOverlord
SlothOverlord

Reputation: 2037

Turns out I had to deconstruct the property of className as ternary operator always returned true for objects

    <NavLink
          className={({isActive}) => //(isActive) --> ({isActive})
            cx(isActive ? classes.linkActive : classes.link)
          }
          to="/seafarers"
          end
        >
          Seafarers
        </NavLink>

Upvotes: 19

Ridwan Ajibola
Ridwan Ajibola

Reputation: 1069

For react-router-dom v6

This example demonstrates how to make a custom <Link> component to render something different when the link is "active" using the useMatch() and useResolvedPath() hooks.

Official doc for active link

Upvotes: 2

Related Questions