NavLink exact prop not working for react-router-dom 6
Answer a question
I am currently using
"react-router": "^6.0.0-beta.0",
"react-router-dom": "^6.0.0-beta.0",
The problem with NavLink of react-router-dom that i am facing now is that the root path "/" is always active, other paths are of no problem and they are being active and inactive during toggle, its just the root path that is giving me trouble, i have searched and tried many solutions. but nothing worked. Use "exact" and "exact={true}" both, but no success.
Used this:
<NavLink
className="iconContainer"
exact={true}
to="/"
activeClassName="isActive"
>
<span className="menu-title">Home</span>
</NavLink>
and Also this:
<NavLink
className="iconContainer"
exact
to="/"
activeClassName="isActive"
>
<span className="menu-title">Home</span>
</NavLink>
I have been stuck in this situation for past two days, and still no success in finding any solution. Any help will be appreciated, thanks
Edit: My routes
<Routes>
<Route
exact
path="order/:orderId"
element={<OrderDetails />}
></Route>
<Route
exact
path="orders"
element={<Orders />}
></Route>
<Route
exact
path="/"
element={<Home />}
></Route>
</Routes>
Answers
Exact param will no longer working on NavLink component. In version 6 Beta they have included a new param called: end
With this simply approach you just need to pass end param for your NavLink component and exact to you Route
<NavLink end to="/">
Go to Home
</NavLink>
When you write end="another-class-active" you can change your active className which is active by default.
As @Greg Wozniak mentioned end is a boolean so you can't change active class name with this, instead of this you can pass a function to className:
className={({ isActive }) =>
isActive ? 'activeClassName' : undefined
}
For more information read this: https://reactrouter.com/docs/en/v6/api#navlink
Working example: https://codesandbox.io/s/vigorous-thompson-e7k8eb
Note that this is still version Beta so we need to wait for some fixes and official releases
更多推荐
所有评论(0)