Blazor - Add Active Class to Current Element

Viewed 5041

Trying to develop a website fully in Blazor

I'm trying to figure out how to add e.g. active class to the currently selected element. I have a side menu bar and it would be awesome to know on which page the user is.

Found this JavaScript solution but I wanted to do it via #c

Any ideas on how to implement it?

5 Answers

Microsoft.AspNetCore.Components.Routing.NavLink component automatically adds "active" class (or a class of a your choosing). Example code below.

<ul class="nav flex-column">
    <li class="nav-item px-3">
        <NavLink class="nav-link" href="" Match="NavLinkMatch.All">
            <span class="oi oi-home" aria-hidden="true"></span> Home
        </NavLink>
    </li>
    <li class="nav-item px-3">
        <NavLink class="nav-link" href="counter">
            <span class="oi oi-plus" aria-hidden="true"></span> Counter
        </NavLink>
    </li>
    <li class="nav-item px-3">
        <NavLink class="nav-link" href="fetchdata">
            <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data
        </NavLink>
    </li>
</ul>

Source: https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.routing.navlink?view=aspnetcore-3.1

as always binding define a property and bind in class="style @prop"

Best way is to use NavMatchLink.All or NavMatchLink.Prefix which sets active class based on the URL, NavMatchLink.All can be used for static or dedicated pages where NavLink href URL matches with display title of link, now if you are Rendering NavLink inside loop, then its better to add Display Title of the link in the URL for ex /ActionMethod/{Parameter}?&Title = {Link Display Name} and use NavMatchLink.Prefix.

Was looking for a solution that didn't require BootStrap and this was the first match. If anyone else is looking at this, remember to include the StateHasChanged() in your EventHandler!!

<button type="button" class="btn btn-nav @isActive" @onclick=NavTo>@display</button>

@code {
    [Inject] NavigationManager _navMan { get; set; }
    [Parameter] public string Destination { get; set; }
    [Parameter] public string Display { get; set; }
    string display => String.IsNullOrWhiteSpace(Display) ? Destination : Display;
    string isActive = "";

    protected override void OnInitialized() {
        _navMan.LocationChanged += UpdateLoc;
    }
    async Task NavTo() {
        _navMan.NavigateTo($"/{Destination}");
    }
    void UpdateLoc(object sender, LocationChangedEventArgs args) {
        isActive = args.Location.Replace(_navMan.BaseUri, "") == Destination ? "active" : "";
        StateHasChanged();
    }
}
Related