blazorblazor-webassembly

Close sidebar automatically when user clicks NavLink


In my Blazor WASM Standalone project, I have a collapsible sidebar used for navigation. I currently keep the state of the sidebar in my centralized state container i.e. isSidebarExpanded = true or false.

I want to make sure whenever a user navigates to a new page by clicking a link i.e. NavLink, I want to automatically close the sidebar.

One idea is to capture the NavLink click event and update the isSidebarExpanded to false.

Alternatively, I can make sure the isSidebarExpanded is set to false in OnInitialized() event in every page but this requires repetitive code.

I'm not sure if these approaches are overly complicating this scenario. I was wondering how others have handled this case.


Solution

  • Inject the NavigationManager and register for the LocationChanged event in your sidebar component. Here's the basic code template:

    @implement IDisposable
    @inject NavigationManager NavigationManager
    
    //...
        protected override void OnInitialized()
        {
            NavigationManager.LocationChanged += OnLocationChanged;
        }
    
        public void Dispose()
        {
            NavigationManager.LocationChanged -= OnLocationChanged;
        }
    
        private void OnLocationChanged(object? sender, LocationChangedEventArgs args)
        {
            //Update State
            StateHasChanged();
        }