Blazor OnClick with JsInterop not working after navigation

41 Views Asked by At

My solution is using per component interactivity. I have a header component that is marked with Interactive auto within the client project. The MainLayout is in the server project.

In that header, I have a button for opening and closing the side menu by using JS interop to call a javascript function.

Whenever I load the page for the first time, the button works. However, any time I navigate to a new page, the button no longer works and no error is displayed in the console.

First, this is how I register the js file containing the function within my MainLayout.razor

<script src="/assets/js/defaultmenu.js"></script>

And this is before I define the blazor script.

The structure is like this: MainLayout (server proj) > Header (client proj) > NavigationToggle (client proj)

The navigation toggle markup looks like this

<div class="">
    <button type="button" class="sidebar-toggle !w-100 !h-100" @onclick="ToggleSidebar">
        <span class="sr-only">Toggle Navigation</span>
        <i class="ri-arrow-right-circle-line header-icon"></i>
    </button>
</div>

With the code behind like this

public partial class NavigationToggle
{
    [Inject] public IJSRuntime Js { get; set; }

    public async Task ToggleSidebar()
    {
        await Js.InvokeVoidAsync("toggleSidemenu");

        StateHasChanged();
    }
}

I'm not sure why navigating to a new page is breaking the behavior.

0

There are 0 best solutions below