Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dark mode of Tailwind CSS does not work with Next.js and styled-jsx #56

Open
FSaldanha opened this issue Jun 24, 2021 · 0 comments
Open

Comments

@FSaldanha
Copy link

(Cross-posting from StackOverflow)

My site is built with Next.js and Tailwind CSS. I followed the default instructions to install them. Since I wanted to customize the appearance of my links without applying inline classes to each one, I also installed styled-jsx-plugin-postcss so that I could use styled-jsx already bundled in Next.js.

It worked almost perfectly, but for some reason the dark mode styles applied in the <style jsx> tag are ignored. I'm using the class strategy as documented. How can I make these styles work?

Below is a sample code from index.js. I also uploaded it to Codesandbox.

import { useState, useEffect } from "react";

export default function IndexPage() {
  const [mounted, setMounted] = useState(false);

  const handleThemeChange = (newTheme) => {
    const bodyClasses = document.body.classList;
    newTheme === "dark" ? bodyClasses.add("dark") : bodyClasses.remove("dark");
    localStorage.theme = newTheme;
  };

  useEffect(() => {
    const defaultTheme =
      localStorage.theme ||
      (window.matchMedia("(prefers-color-scheme: dark)").matches
        ? "dark"
        : "light");
    handleThemeChange(defaultTheme);
    setMounted(true);
  }, []);

  if (!mounted) return null;

  return (
    <div className="dark:bg-black dark:text-white text-xl">
      <ul className="cursor-pointer mb-6">
        <li
          onClick={() => handleThemeChange("dark")}
          className="block dark:hidden"
        >
          Click to activate dark mode
        </li>
        <li
          onClick={() => handleThemeChange("light")}
          className="hidden dark:block"
        >
          Click to activate light mode
        </li>
      </ul>
      <p>
        <a href="#">This link</a> should be red in dark mode.
      </p>
      <style jsx>{`
        a {
          @apply text-green-500 dark:text-red-500;
        }
      `}</style>
    </div>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant