Flux has always supported dark mode in the sense that when your system appearance changes, Flux adapts.
However, there's a big gap between that kind of dark mode support, and providing controls to fully control dark mode for a site independently of system preferences.
Before we get into the details, just take a look at how simple it is now to create a dark mode switcher like the one shown above. Here is the exact code that was used for that switcher:
Here's another code snippet to make an even simpler toggle button:
New JavaScript APIs
As you might have noticed in the code snippets above, Flux now ships with a magic
$flux
object available to you inside Alpine expressions.
There are two dark-mode related affordances on this magic object:
.dark
and
.appearance
.
You can get/set the dark state of an app using the
$flux.dark
boolean property. You can also get/set the theme preference for an app using the
$flux.appearance
property (which will be one of three values:
light
,
dark
, and
system
).
Given these two simple properties, you should be able to accomplish any type of dark mode control widget you'd like. For example, a dark mode select, a dropdown menu, a toggle button, a toggle switch, radio groups, cards, or segmented radios. The sky's the limit.
If you need control from outside of Alpine, we've also shipped a global Flux object on the window called
window.Flux
.
Now, you can do something like this:
What's going on under the hood?
Out of the box, Flux will add/remove a
.dark
class to the
<body>
element of your page.
This means you can easily configure Tailwind to honor this class instead of the system preference using Tailwind configuration like so:
Flux takes care of all the tricky bits like storing the user appearance preference in local storage to persist that choice between page loads.
We are also listening for system preference changes at run-time so that we can adapt the site without waiting for a new page load.
Doing these things yourself is not rocket science, but it certainly is more complicated than you want it to be. Enjoy.