Nov 05 2024
In your tailwind.config.js
1export default {2 darkMode: 'class',3 ...4}
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 : false10 }11}"12x-init="getCurrentTheme()"13x-on:toggledm.window="toggleDarkMode()"14x-bind:class="darkMode ? 'dark' : ''">
x-init
dark
class from the body.1<button x-on:click="$dispatch('toggledm')">2 <div x-show="darkMode" class="text-gray-400">3 // Add your moon icon here4 // heroicons.com has some good ones5 </div>6 <div x-show="!darkMode" class="text-gray-400">7 // Sun icon here8 </div>9</button>
You can simplify this example even more by not dispatching an event and just doing the whole operation in the button.