ThemeToggle
A one-click light/dark mode switcher. Writes the selected mode to localStorage and applies the dark class to any data-dark-mode-target element. Re-applies the stored preference after Blazor enhanced navigations.
Installation instructions
-
Register the BlazorUI services in
Program.cs— this provides the scopedGlobalThemestate that ThemeToggle binds to:builder.Services.AddSitecoreBlokUI(); -
Place the
<ThemeToggleStartupScript />inside<head>inApp.razor. It runs synchronously before body parse and applies the stored theme to<html>, preventing a flash of light content on load:<head> ... <ThemeToggleStartupScript /> </head> -
Mark the element you want the
darkclass applied to withdata-dark-mode-target— usually the root of yourMainLayout:<div data-dark-mode-target class="text-foreground"> @Body </div> - Drop
<ThemeToggle />into your header or anywhere else you want the switcher to live.
Divergence from Blok
Blazor-side addition; no equivalent in the Blok design system. Blok ships a theme toggle as a one-off site-chrome component within their docs site. We package the equivalent here as a reusable BlazorUI primitive that any consumer can drop in.
Examples
Default
How it works
Add the data-dark-mode-target attribute to any container you want the dark class applied to (commonly the root layout element). The toggle writes the user's selection to localStorage.displayMode so it survives reloads.
The toggle subscribes to Blazor's enhancedload event and re-applies the stored preference after every enhanced navigation — without this, the server-rendered HTML diff would strip the dark class during client-side route changes.
API
The element family below can be composed together. Click an element to jump to its properties.
| Element | Purpose |
|---|---|
| ThemeToggle | A small Toggle-based sun/moon switcher that flips the scoped GlobalTheme between light and dark, and persists the choice in localStorage. |
| ThemeToggleStartupScript | Inline <script> that reads localStorage.displayMode and applies the dark class to <html> before the body parses, preventing a flash of light-themed content on first paint. Drop it inside <head> once per app. |
ThemeToggle
A small Toggle-based sun/moon switcher that flips the scoped GlobalTheme between light and dark, and persists the choice in localStorage.
| Property | Type | Required | Description |
|---|---|---|---|
| ClassName | string? | Extra CSS classes appended to the underlying Toggle button. |
ThemeToggleStartupScript
Inline <script> that reads localStorage.displayMode and applies the dark class to <html> before the body parses, preventing a flash of light-themed content on first paint. Drop it inside <head> once per app.
This element has no public parameters.