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>
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
In 6.0.2 you can pass a function to className and that function gets a set of props. One of those props is "isActive". Here is how I solved it for the OP code:
<NavLink
className={(props) => {
return `${props.isActive ? 'isActive ' : ''}iconContainer`;
}}
end
to="/"
>
<span className="menu-title">Home</span>
</NavLink>
Also note that the class "active" is automatically set by the NavLink.
Also note the use of end: "If the end prop is used, it will ensure this component isn't matched as "active" when its descendant paths are matched. For example, to render a link that is only active at the website root and not any other URLs"
However this how I did it, you don't have to use exact in the case of NavLink
as said by the official docs, LINK TO THE DOCS
<NavLink to="/service" className='turner'>
Services
</NavLink>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.