Blazor WASM Dark Theme and Light Theme
blazor
20 Articles
Dark Mode or Theme has become common nowadays. Almost all the operating system, apps and websites started supporting Dark Mode as first class feature as it gives a pleasing experience to eyes when reading or using the app at night time. So it's time to design dark version of apps or website to go along with the default design. Let's see how we can implement this in Blazor application.
First, lets have a enum
DisplayMode
to represent different display modes.
Next, we need the help of Javascript
here to add
respective CSS class to our document based on the option we select. We can select
Light
mode,
Dark
mode or
System
mode to let it detect based on operating
systems default display mode.
Code Sample - Display Theme Component to toggle Display Mode
When we click on button to set theme or mode, SetTheme(DisplayMode displayMode)
method is called by Blazor
which in turn will use
JavaScript
to call
onDisplayModeChanged
function. If the selected
DisplayMode
is
Dark
or
System
and if the operation system has dark theme enabled? then we can set
dark
CSS Class to HTML
document and store the user preference in Local Storage
to retain it for
next time when the user visits our app.
If the user has selecetd Light
DisplayMode
then we can remove the
dark
CSS Class from the
HTML
document and also remove the entry from
Local Storage
.
Code Sample - Javascript function to store and toggle CSS class
Now that all set, we need to make sure to load the user preference when the user visits our site anytime in future. For this we
can again use small Javascript
on page load in our
index.html
to check if the
Local Storage
entry has
DisplayMode
key with
dark
value or we can check if the operating system
supports Dark
mode. In both case we can add
dark
CSS class back to
HTML
document. If both the above cases are not met then,
we can leave it to default light theme.
Code Sample - Javascript to toggle display mode CSS class on page load
Time for a live demo. Try with below demo and make sure to inspect and see how CSS classed are toggled in
HTML
along with
Local Storage
changes.
Demo - Display Mode
Click on one of the display mode and see how the I ❤️ DotNet responds.