NET8 Blazor components and render mode

Enrico Rossini 201 Reputation points
2023-12-12T12:07:27.0466667+00:00

I'm creating a Blazor component to have a NuGet package of the design. So, I can use it in different projects. I have a Razor called TopNavBar that displays the header of the page.

<div class="top-navbar style-1">
    <div class="container p-0">
        <div class="row align-items-center">
            <div class="title">
                @Title
            </div>
            <div class="col-lg-4">
                <DarkLightSwitch />
            </div>
        </div>
    </div>
</div>

As you can see, there is another reference to a DarkLightSwitch razor page. This is a simple switch to select a dark mode for the website. If the user clicks on the dark mode, the component has to call a JavaScript function to change the color for the all website.

@inject IJSRuntime jsRuntime

<div class="darkLight-btn">
    <span class="icon @(IsDarkTheme ? "" : "active")" 
        id="light-icon" @onclick="OnLightClick">
        <i class="la la-sun"></i>
    </span>
    <span class="icon @(IsDarkTheme ? "active" : "")" 
        id="dark-icon" @onclick="OnDarkClick">
        <i class="la la-moon"></i>
    </span>
</div>

@code {
    /// <summary>
    /// Is the dark theme activate?
    /// </summary>
    [Parameter] public bool IsDarkTheme { get; set; } = false;

    protected async Task OnLightClick(MouseEventArgs args)
    {
        await jsRuntime.InvokeVoidAsync("switchToLight");
        IsDarkTheme = false;
    }

    protected async Task OnDarkClick(MouseEventArgs args)
    {
        await jsRuntime.InvokeVoidAsync("switchToDark");
        IsDarkTheme = true;
    }
}

When I add the TopNavBar to a MainLayout.razor or any other page, if I click on the DarkLightSwitch nothing is happening because the page is rendered in a static mode.

If in the TopNavBar I call the DarkLightSwitch like this

<DarkLightSwitch @rendermode="RenderMode.InteractiveAuto" />

at run-time the component is not be found.

enter image description here

If I add the @rendermode to the TopNavBar, the entire Razor page is not found.

Is there a way to fix it?

Developer technologies | .NET | Blazor
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.