styled-jsx-plugin-postcss
styled-jsx-plugin-postcss copied to clipboard
Dark mode of Tailwind CSS does not work with Next.js and `styled-jsx`
(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>
);
}