NavLink component stays active?

Viewed 34

A navlink to homepage always stays active. Other 2 navlinks work correctly and only added an active style when chosen. Is there any problem with routes or function that changes the active link?

const activeStyles = {
  color: 'green',
};

<ul className="flex gap-8">
  <li>
    <NavLink
      to={"/"}
      className="text-xs text-gray-400 hover:text-white"
      style={({ isActive }) => (isActive ? activeStyles : undefined)}
    >
      Main
    </NavLink>
  </li>
  <li>
    <NavLink
      to={"posts"}
      className="text-xs text-gray-400 hover:text-white"
      style={({ isActive }) => (isActive ? activeStyles : undefined)}
    >
      My Posts
    </NavLink>
  </li>
  <li>
    <NavLink
      to={"new"}
      className="text-xs text-gray-400 hover:text-white"
      style={({ isActive }) => (isActive ? activeStyles : undefined)}
    >
      Add post
    </NavLink>
  </li>
</ul>

after clicking on the add post Navlink, main still stays active

2 Answers

For react-router v6, if you want your root route ("/") to be active only at this route, you should add an end prop to <NavLink>:

<NavLink to="/" end>
  Main
</NavLink>

For this you have to use exact key work in Navlink like this:

<NavLink to='/' exact={true}>
   Main
 </NavLink>

because'/' is active for all routes that's why you are getting this.

Related