The Best

👜 Categories

🔗 Links

Tailwindcss manual dark mode

shahriyardx
July 18, 2022

Config

To enable the manual dark mode feature in your tailwindcss website first add darkMode: 'class' in your tailwind.config.js file

module.exports = {
    darkMode: 'class',
    ...
}

Hook

Then we have to create a custom hook for getting the current theme and toggling the theme.

import { useEffect, useState } from "react"

const themes = {
  dark: 'light',
  light: 'dark'
}

const useTheme = () => {
  const [theme, setTheme] = useState('dark')

  const toggleTheme = () => {
    const _theme = themes[theme]
    localStorage.setItem('theme', _theme)
    updateTheme(_theme)
  }

  const updateTheme = (name) => {
    setTheme(name)
    document.querySelector('html')
      ?.classList.remove(themes[name])
    
    document.querySelector('html')
      ?.classList.add(name)
  } 
  useEffect(() => {
    const _theme = localStorage.getItem('theme') || 'dark'
    updateTheme(_theme)
  }, [])

  return { theme, toggleTheme }
}

export default useTheme;

Import and use

Finally, we can import the useTheme hook in any of our components and bind the toggleTheme function with a button or any element. Whenever we call the toggleTheme function it will change the website's theme to the opposite.

function ThemeButton() {
    const { toggleTheme } = useTheme()

    return (
        <button onClick={toggleTheme}>Change Theme</button>
    )
}