Dark Mode Toggle With Alpine and Tailwind

Published Nov 05 2024

Enable dark mode on tailwind

In your tailwind.config.js

export default {
    darkMode: 'class',
    ...
}

Add some alpinejs to your body

<body class="font-sans antialiased"
x-data="{
	darkMode: false,
	toggleDarkMode: function() {
		this.darkMode = !this.darkMode
		localStorage.setItem('color-theme', this.darkMode ? 'dark' : 'light')
	},
	getCurrentTheme() {
		this.darkMode = (localStorage.getItem('color-theme') == 'dark') ? true : false
	}
}"
x-init="getCurrentTheme()"
x-on:toggledm.window="toggleDarkMode()"
x-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

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

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