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?
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");
}
}