Home > OS >  Why React Router NavLink prop exact (v5) vs. end (v6) lead to different result with trailing slash i
Why React Router NavLink prop exact (v5) vs. end (v6) lead to different result with trailing slash i

Time:01-02

In React Router Version 5 I had a NavLink which looked the following:

<NavLink
  to="/notes"
  exact={true}
  className="border-transparent text-gray-600 hover:bg-gray-50 hover:border-gray-300 hover:text-gray-800 block pl-3 pr-4 py-2 border-l-4 text-base font-medium"
  activeClassName="bg-indigo-50 border-indigo-500 text-indigo-700 block pl-3 pr-4 py-2 border-l-4 text-base font-medium"
>
  Home
</NavLink>

It recognized both localhost:3000/notes and localhost:3000/notes/ with a trailing slash as active urls.

In React Router Version 6 I refactored it to the following:

<NavLink
  to="/notes" end
  className={(navData) =>
  navData.isActive
    ? "bg-indigo-50 border-indigo-500 text-indigo-700 block pl-3 pr-4 py-2 border-l-4 text-base font-medium"
    : "border-transparent text-gray-600 hover:bg-gray-50 hover:border-gray-300 hover:text-gray-800 block pl-3 pr-4 py-2 border-l-4 text-base font-medium"
  }
>
  Home
</NavLink>

This recognizes only localhost:3000/notes as active url.

Is there a way in v6 to have also the version with trailing slash recognized as an active url?

CodePudding user response:

I think you've mixed up what the react-router-dom v5 exact prop represents, or rather, that you've conflated the behavior between the Edit why-react-router-navlink-prop-exact-v5-vs-end-v6-lead-to-different-result-w

CodePudding user response:

put exact instead of end

import React from 'react';
import {
  BrowserRouter as Router,
  Routes,
  Route,
  NavLink,
} from 'react-router-dom';
import './style.css';

const Users = () => <div>Users</div>;
const Posts = () => <div>Posts</div>;

const App = () => {
  return (
    <div className="app">
      <Router>
        <div className="nav">
          <NavLink
            to="users"
            exact
            style={({ isActive }) =>
              isActive
                ? {
                    color: '#fff',
                    background: '#7600dc',
                  }
                : { color: '#545e6f', background: '#f0f0f0' }
            }
          >
            Users
          </NavLink>
          <NavLink
            to="posts"
            style={({ isActive }) =>
              isActive
                ? {
                    color: '#fff',
                    background: '#7600dc',
                  }
                : { color: '#545e6f', background: '#f0f0f0' }
            }
          >
            Posts
          </NavLink>
        </div>
        <Routes>
          <Route path="users" element={<Users />} />
          <Route path="posts" element={<Posts />} />
        </Routes>
      </Router>
    </div>
  );
};

export default App;

  • Related