<NavLink
className={({ isActive }) => (isActive ? "isActive" : "isNotActive")}
to={"artist/" + currentMotive.artist.slug.current}
key={currentMotive.artist.slug.current}>
{currentMotive.artist.name}
</NavLink>
How can I change the attribute to
in the same way as className
?
Like:
to={({ isActive }) =>
isActive
? "/motive/" + currentMotive.slug.current
: "artist/" + currentMotive.artist.slug.current
}
I use react router 6.8.
I tried to use useLocation
to check the path and compare it, but isn’t there an easier way?
Here is the code:
https://codesandbox.io/s/toogle-navlink-p5plsq?file=/src/RootLayout.js
I want, that in the Nav, Artist 1 works like a toggle to open and close <Artist />
2
Answers
You can use useMatch to check if the path is active.
You can create a state in the layout to hold a reference to an active artist and attach an
onClick
handler to each link to set the active artist value. Theto
prop would conditionally render the appropriate link target.Example:
Example from sandbox: