Give the sidebar the current location in activePath. It marks the item or
sub-item whose link points there, and keeps doing so when the location, the
links or the items change. You don't set active on any item yourself.
Nested source
How a link is matched#
- The match is exact.
activePathis compared with the link'shrefattribute as it is rendered./reportsdoes not match/reports/2024,/reports/or/reports?tab=1. - Items without an
hrefare left alone. That includes parents that use a<span>as their label. You can setactiveon those yourself. - Without
activePaththe sidebar marks nothing. Setactiveon items yourself if you prefer. ClearingactivePathlater removes only the highlights it had set. - Changes are followed. A new
activePath, a link that gets anotherhrefand items added later are all matched right away.
Because the comparison uses the rendered href, pass the path in the same
form your links have. A router that serves the application below a base path
renders that base path into the href, so it has to be part of activePath
too.
Parents and sub-items#
A parent is not marked because one of its sub-items is. What you see depends on whether the active sub-item is visible:
| State | What is highlighted |
|---|---|
| Parent open | The sub-item |
| Parent closed | The parent |
| Sidebar collapsed to the icon rail | The parent |
Try it in the example above: close Projects while Atlas is the current page.
A parent that is active in its own right, because its own link matches or you
set active, stays active in every state.
Keep a section active on deeper routes#
The exact match means /projects/42/settings marks nothing if the sidebar
only links to /projects. Map the location to the entry it belongs to before
you pass it on:
const sections = ['/dashboard', '/projects', '/settings'];
function sectionOf(pathname: string) {
return (
sections.find(
(section) => pathname === section || pathname.startsWith(`${section}/`),
) ?? pathname
);
}
Connect it to a router#
NavLink renders the href as you wrote it, so compare it with the path
relative to the base address:
@implements IDisposable
@inject NavigationManager Navigation
<NvSidebar ActivePath="@path">
<NvSidebarcontent>
<NvSidebarnavitem Icon="NvIcon.NameEnum.home">
<NavLink href="dashboard">Dashboard</NavLink>
</NvSidebarnavitem>
</NvSidebarcontent>
</NvSidebar>
@code {
private string path = "";
protected override void OnInitialized()
{
path = Navigation.ToBaseRelativePath(Navigation.Uri);
Navigation.LocationChanged += OnLocationChanged;
}
private void OnLocationChanged(object? sender, LocationChangedEventArgs e)
{
path = Navigation.ToBaseRelativePath(e.Location);
StateHasChanged();
}
public void Dispose() => Navigation.LocationChanged -= OnLocationChanged;
}
What assistive technology gets#
The active item and the active sub-item carry aria-current="page". A
collapsible parent never does, also when it is highlighted for a hidden
sub-item: the current page is inside it, and it exposes aria-expanded
instead.