giuseppeg / giuseppeg/styled-jsx-plugin-postcss

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

Open
#56 0 comments 2 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
90
Forks
16
PR merge metrics
No merged PRs in 30d

Description

(Cross-posting from [StackOverflow](https://stackoverflow.com/questions/68115888/how-to-make-dark-mode-of-tailwind-css-work-with-next-js-and-styled-jsx))

My site is built with Next.js and Tailwind CSS. I followed the [default instructions](https://tailwindcss.com/docs/guides/nextjs) 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`](https://github.com/giuseppeg/styled-jsx-plugin-postcss) so that I could use `styled-jsx` [already bundled](https://nextjs.org/docs/basic-features/built-in-css-support#css-in-js) in Next.js.

It worked almost perfectly, but for some reason the dark mode styles applied in the `` tag are ignored. I'm using the `class` strategy [as documented](https://tailwindcss.com/docs/dark-mode#toggling-dark-mode-manually). How can I make these styles work?

Below is a sample code from `index.js`. [I also uploaded it to Codesandbox.](https://codesandbox.io/s/tailwindcss-stlyedjsx-nextjs-morb7?file=/pages/index.js)

```javascript
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;
}
`}

);
}
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.