I am trying to make my nested route tab active when first displayed but it does not become active unless clicked. If I change anything the parent route becomes inactive.
App.js
<Route path="account" element={<Account />}>
<Route index element={<Profile />} />
<Route path="profile" element={<Profile />} />
<Route path="key" element={<Key />} />
</Route>
The reason I have profile as index is because I want that tab to be open as default when user navigates to "/account"
from the left nav.
LeftNav.js
<NavLink to='account' className="nav-link" activeClassName="active">
<span>Account</span>
</NavLink
By default the profile component is loaded which is great but I have another tab inside to switch between profile and key and that is where the profile is not highlighted/active.
Account.js
<div>
<Header title="Account" />
<div>
<NavAccount />
</div>
</div>
Account.js is the page that displays the nested routes swticher for the user.
NavAccount.js
<div>
<div>
<ul className="nav nav-tabs" role="tablist">
<li className="nav-item">
<NavLink
to='profile'
className="nav-link"
id='profileTab'
data-bs-toggle="pill"
activeclassname="active"
>
<span>Profile</span>
</NavLink>
</li>
<li className="nav-item">
<NavLink
to='key'
className="nav-link"
id='apiKeyTab'
data-bs-toggle="pill"
activeclassname="active"
>
<span>API Key</span>
</NavLink>
</li>
</ul>
</div>
<Outlet />
</div>
As you can see below, the profile tab when first displayed it not active until clicked.
Things I tried:
- I changed the
Navlink
inLeftNav.js
to point toto='account/profile'
which worked, but I when I clicked on API key tab, the parent route (in the left nav) became inactive.
2
Answers
Use end prop
From what I understand of this and the code it seems you would like to make the
"/account/profile"
route a "default" route such that when navigating to"/account"
via the left-nav that theProfile
page will be "active". For this you can render a redirect to"/account/profile"
on the"/account"
index route."/account"
link inLeftNav
will be active for being on any"/account/*"
path"/account/profile"
link inNavAccount
will be active for being the currently matched path.Also just FYI, the
react-router-dom@6
NavLink
component hasn’t anyactiveClassName
prop, it was removed. The RRDv6NavLink
applies an"active"
CSS classname by default for the matched route.If you wanted to use a different CSS classname for the active class then use the function callback form of the
className
prop.