2

I'm working on my first Blazor WASM app and I need to programmatically set/change classes for the <body> tag which is in index.html. For example, setting the light/dark theme is done through setting the appropriate class for the <body> tag.

Is this possible only through JS Interop or is there another way to handle it?

3
  • It's not done through <body> or index.html, on any SPA. The web page only shows a spinner and loads the Javascript/WASM of the applications. Anything you see is drawn by the application, including styles and theming. If you google for Blazor Themes you'll find a lot of results, mainly from component suites that offer their own theme support Commented Aug 30, 2023 at 17:26
  • At least one way to change themes is to change the Layout or DefaultLayout` values in App.razor. Those are normal component parameters and can be bound and changed the same way any other parameter can Commented Aug 30, 2023 at 17:30
  • I'm using a professionally designed HTML/jQuery template and that's how the designer handled it. He even handled the nav bar through classes in the <body> tag. So, using this particular HTML template requires me to manipulate the <body> tag classes. Commented Aug 30, 2023 at 17:45

1 Answer 1

2

No, body is outside the Blazor DOM Scope. However, it's relatively easy with JsInterop.

site.js registerted in index.html or _Host.cshtml.

window.Blazr = {
    setCssClass: function (elementId, css) {
        var link = document.getElementById(elementId);
        link.className = css;
        return true;
    }
}

A service:

public class BlazrInteropLibrary
{
    protected IJSRuntime JSRuntime { get; }

    public BlazrInteropLibrary(IJSRuntime jsRuntime)
        => JSRuntime = jsRuntime;

    public ValueTask<bool> SetCssClass(string elementId, string css)
        => JSRuntime.InvokeAsync<bool>("Blazr.setCssClass", elementId, css);
}

Registered:

builder.Services.AddScoped<BlazrInteropLibrary>();

Set the id of <body> to "blazorBody".

And a simple demo page.

@page "/"
@inject BlazrInteropLibrary BlazrJs

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />
<div>
    <button class="btn btn-primary" @onclick="ChangeBody">Change</button>
</div>

@code {
    private async Task ChangeBody()
    {
       await BlazrJs.SetCssClass("blazorBody", "black-background");
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

NP - you've helped many others. It's a version of this - shauncurtis.github.io/Building-Blazor-Applications/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.