Nov 05 2024

Dark mode toggle with Alpine and Tailwind


Enable dark mode on tailwind

In your tailwind.config.js

1export default {
2    darkMode: 'class',
3    ...
4}

Add some alpinejs to your body

1<body class="font-sans antialiased"
2x-data="{
3 darkMode: false,
4 toggleDarkMode: function() {
5 this.darkMode = !this.darkMode
6 localStorage.setItem('color-theme', this.darkMode ? 'dark' : 'light')
7 },
8 getCurrentTheme() {
9 this.darkMode = (localStorage.getItem('color-theme') == 'dark') ? true : false
10 }
11}"
12x-init="getCurrentTheme()"
13x-on:toggledm.window="toggleDarkMode()"
14x-bind:class="darkMode ? 'dark' : ''">
  1. We get the previously selected theme (if any) on page load using x-init
  2. Every time we toggle we save the new value and add/remove the dark class from the body.

Basic dark mode toggle for in the nav bar

1<button x-on:click="$dispatch('toggledm')">
2 <div x-show="darkMode" class="text-gray-400">
3 // Add your moon icon here
4 // heroicons.com has some good ones
5 </div>
6 <div x-show="!darkMode" class="text-gray-400">
7 // Sun icon here
8 </div>
9</button>

You can simplify this example even more by not dispatching an event and just doing the whole operation in the button.