Search code examples
c#blazor

How do i set "nav-item active" in Blazor?


I'm building an application using Blazor & Bootstrap. I want to use a standard bootstrap navbar. I can't figure out how to add the "active" class to the <li> tag selected.

This is my code:

<div class="collapse navbar-collapse">
    <ul class="navbar-nav">
        <li class="nav-item">
            <NavLink class="nav-link" href="" Match="NavLinkMatch.All">Home</NavLink>
        </li>
        <li class="nav-item">
            <NavLink class="nav-link" href="/counter" Match="NavLinkMatch.All">Counter</NavLink>
        </li>
        <li class="nav-item">
            <NavLink class="nav-link" href="/fetchdata" Match="NavLinkMatch.All">Fetch data</NavLink>
        </li>
    </ul>
</div>

The built in <NavLink> which is a blazor component changes the class for the <a/> automatically. But since i am using bootstrap navbar i need to add "active" to the class of the selected <li>.

This is how it should look like when the link is active:

 <li class="nav-item active">
    <NavLink class="nav-link" href="" Match="NavLinkMatch.All">Home</NavLink>
 </li>

Solution

  • You could use the navigation manager:

    <li class="nav-item @GetActive("", NavLinkMatch.All)">
        <NavLink class="nav-link" href="" Match="NavLinkMatch.All">Home</NavLink>
    </li>
    
    @code {
    
        [Inject]
        NavigationManager NavigationManager { get; set; }
    
        protected override void OnInitialized() => NavigationManager.LocationChanged += (s, e) => StateHasChanged();
    
        bool IsActive(string href, NavLinkMatch navLinkMatch = NavLinkMatch.Prefix)
        {
            var relativePath = NavigationManager.ToBaseRelativePath(NavigationManager.Uri).ToLower();
            return navLinkMatch == NavLinkMatch.All ? relativePath == href.ToLower() : relativePath.StartsWith(href.ToLower());
        }
    
        string GetActive(string href, NavLinkMatch navLinkMatch = NavLinkMatch.Prefix) => IsActive(href, navLinkMatch) ? "active" : "";
    }