Posted on • Updated on

Next js Toggle Taiwind Css Theme

author

Kai

Step 1 - Setup “tailwind.config.js”

module.exports = {
 	...
  	darkMode: "class",
  	...
};

Step 2 - Make Changes in the header component.

import React, { useEffect, useState } from "react";

export default function Header() {
  const [theme, setTheme] = useState("");

  /* Toggle Method */
  const toggleTheme = () => {
    if (localStorage.theme == "light") {
      localStorage.setItem("theme", "dark");
      document.documentElement.classList.add("dark");
    } else {
      localStorage.setItem("theme", "light");
      document.documentElement.classList.remove("dark");
    }
    setTheme(localStorage.theme);
  };
  
  /* Set Current theme Method */
  const setCurrentTheme = () => {
    if (
      localStorage.theme === "dark" ||
      (!("theme" in localStorage) &&
        window.matchMedia("(prefers-color-scheme: dark)").matches)
    ) {
      setTheme("dark");
      document.documentElement.classList.add("dark");
    } else {
      document.documentElement.classList.remove("dark");
    }
  };

 /*Call setCurrentTheme when page load */
  useEffect(() => {
    setCurrentTheme();
  });
  
  return(
  	<header>
  	...
  	{/* theme toggle btn */}
  	<button className="nav-link" onClick={toggleTheme}>
    	{theme !== "dark" ? (
    	moon icon
    	) : (
      	sun icon
    	)}
  	</button>
	...
  	</header>
  )
 }
end of article

Related Posts

Join Our Newsletter

Want the latest & greatest from our blog straight to your inbox with some exclusive offers from our partners and sponsors?

We won't spam. Promise.