This post assumes that you know how to add Tailwind CSS in a Blazor Application. Read this post if you don't already!
In this notebook, we'll explore the implementation of a class-based theme changer for Blazor applications using Tailwind CSS. This approach allows us to seamlessly switch between light and dark themes while leveraging the power and simplicity of Tailwind CSS for styling.
Tailwind CSS is a popular utility-first CSS framework that enables rapid UI development by providing a set of pre-defined classes. Blazor, on the other hand, is a framework for building interactive web UIs using C# instead of JavaScript. By combining Tailwind CSS with Blazor, we can create modern and responsive web applications efficiently.
One common feature in web applications is the ability to switch between different themes, such as light and dark themes. In this notebook, we'll demonstrate how to implement a theme changer using Tailwind CSS classes in a Blazor application.
Create a Blazor Server App. Create a razor component in a new folder named widget. This is the component that toggles between light and dark theme.
We have injected the IJSRuntime so that we can call a javascript function, which will toggle the dark class on the document. For the javascript function i.e. toggleTheme, we have created an app.js file in the wwwroot and added the following script,
Add the script in the App.razor file. Notice that we have added some classes to the <body>.
flowbite is a component library based on Tailwind CSS. It is optional.
The AppState service is a class having a string property that stores the current theme. It is registered with the scoped lifecycle,
We should store the theme in the browser's local storage, so that when a user re-opens the app, the previously selected theme is persisted. Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage package could be used for that purpose.
Import it in the _Imports.razor file,
The tailwind.config.js file should look like this,
Comments