JSFiddle - React, Tailwind, and code Playground

by Michel Plungjan

HTML

<html>
<head>


<script> // script needs to be in the head
    const theme = localStorage.getItem("theme") || "theme"
    if (theme === "dark") {
      const st = document.createElement("style");
      st.id="darkStyle";
      st.innerText = `body.theme { background-color: black; color: white; }`;
      document.querySelector("head").appendChild(st);
    }

    window.addEventListener("load", function() {
      document.getElementById("toggleTheme").addEventListener("click", function() {
        const body = document.querySelector("body");      
        const darkStyle = document.getElementById("darkStyle");
        if (darkStyle) {
          darkStyle.remove(); // remove stylesheet now we know what the user wants
          body.classList.remove("theme");
        }  
        const theme = body.classList.contains("theme"); 
        body.classList.toggle('theme',!theme);
        body.classList.toggle('dark',theme);
        localStorage.setItem("theme", theme ? "light" : "dark"); // uncomment on your server
      });
    })
  </script>
  </head>
 <body class="theme">
  Here is the body

  <button id="toggleTheme" type="button">Toggle theme</button>
</body>

</html>

CSS

.dark { background-color: black; color: white; }