Articles in this section
Category / Section

How to change Blazor App Theme in Button Click?

1 min read

This article explains how to change theme on button click in Blazor application. The following steps provide the detailed information to create a Blazor application that change theme on button click from light theme to dark theme and vice versa.

1. Create a Blazor application with Syncfusion NuGet packages referring the Blazor getting started documentation.

2. Refer the below code snippets to refer stylesheet in the application to change the theme on button click. Add the code in “_Layout.cshtml” page in .NET 6 Blazor Server Application, and in “index.html” page in Blazor Web Assembly Application.

<head>
    ...
    <link id="theme" href="https://cdn.syncfusion.com/blazor/20.1.61/styles/fluent.css" rel="stylesheet"/>
    ...
</head>
...
    <script>
        function setTheme(theme) {
            document.getElementsByTagName('body')[0].style.display = 'none';  
            let synclink = document.getElementById('theme');
            synclink.href = 'https://cdn.syncfusion.com/blazor/20.1.61/styles/' + theme + '.css';
            setTimeout(function () { document.getElementsByTagName('body')[0].style.display = 'block'; }, 200);
        }
    </script>
...

 

3. Now modify the MainLayout.razor page with the below code to implement a theme change on button click from light theme to dark theme and vice versa.

@inherits LayoutComponentBase
@inject IJSRuntime JS
 
<PageTitle>ChangeTheme</PageTitle>
 
@using Syncfusion.Blazor.Buttons
 
<div class="page">
     <div class="sidebar">
          <NavMenu />
     </div>
 
     <main>
          <div class="top-row px-4">
               <SfButton IsPrimary="true" Content="@Content" IsToggle="true" @onclick="changeTheme" @ref="ToggleBtnObj"></SfButton>
               <a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a>
          </div>
 
          <article class="content px-4">
               @Body
          </article>
     </main>
</div>
 
@code{
     SfButton ToggleBtnObj;
 
     public string Content = "Light";
 
     public void changeTheme()
     {
          if(ToggleBtnObj.Content == "Light")
          {
                this.Content = "Dark";
                JS.InvokeAsync<object>("setTheme", "fluent-dark");
          }
          else
          {
                this.Content = "Light";
                JS.InvokeAsync<object>("setTheme", "fluent");
          }
     }
}

 

View Sample in GitHub

 

See also

Blazor themes

Blazor theme studio

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied