Here's one way to do it. This example is based on a default Blazor Server project, with the Index.razor, Counter.razor, and FetchData.razor components/pages.
Add a scripts folder to your wwwroot, if you don't already have one, add a new JavaScript file called 'body-class-changer.js" and insert the following code
window.bodyClassMethods = {
setBodyClass: function (bodyClass) {
document.body.classList.value = bodyClass;
}
}
Add a script tag to the bottom of your _Host.cshtml file, just above the closing body tag
<script src="~/scripts/body-class-changer.js"></script>
Add a class file to your Shared folder called "ClassSelector.cs" and adjust the class with the following code
public class ClassSelector
{
public static string GetClass(string currentPage)
{
switch (currentPage)
{
case "":
return "home-class";
case "counter":
return "counter-class";
case "fetchdata":
return "fetchdata-class";
}
return string.Empty;
}
}
Add a new Razor Component to your Shared folder called "ClassChanger.razor" with the following code
@inject NavigationManager navigationManager
@inject IJSRuntime jsRuntime
@implements IDisposable
@code {
string bodyClass { get; set; }
protected override void OnInitialized()
{
navigationManager.LocationChanged += OnLocationChangedAsync;
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
bodyClass = Shared.ClassSelector.GetClass(navigationManager.ToBaseRelativePath(navigationManager.Uri));
await jsRuntime.InvokeVoidAsync("bodyClassMethods.setBodyClass", bodyClass);
}
}
public void Dispose()
{
navigationManager.LocationChanged -= OnLocationChangedAsync;
}
private async void OnLocationChangedAsync(object sender, LocationChangedEventArgs args)
{
bodyClass = Shared.ClassSelector.GetClass(navigationManager.ToBaseRelativePath(navigationManager.Uri));
await jsRuntime.InvokeVoidAsync("bodyClassMethods.setBodyClass", bodyClass);
StateHasChanged();
}
}
Then add this Razor Component to the bottom of your MainLayout.razor file
<ClassChanger></ClassChanger>