Simple theming for Next.js apps using the App Directory.
npm install next-app-themeSimple theming for Next.js apps using the App Directory.
- No flashing on page load
- Works with tailwind
> NOTE: You can actually use this package outside of Next.js. In essence it'js just a script that executes in the head of your page. So you can just use ThemeScript and the global __setPreferredTheme.
``bash`
npm install next-app-theme
First add the script to your root layout.
Make sure to add it to the
of your page so that it runs before your app.app/layout.js:`tsx
import { ThemeScript } from "next-app-theme/theme-script";export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
{children}
);
}
`Then use the theme in your
app/global.css:`css
.light {
color-scheme: light;
}.dark {
color-scheme: dark;
}
`Then create a component to toggle the theme:
`tsx
"use client";import { useTheme } from "next-app-theme/use-theme";
import { Sun, Moon } from "lucide-react";
function ThemeToggle() {
const { theme, toggleTheme } = useTheme();
const icon = theme === "dark" ? : ;
return ;
}
`Then use the toggle somewhere in your app:
`tsx
// Don't SSR the toggle since the value on the server will be different than the client
const SetThemeButton = dynamic(() => import("./ui/SetThemeButton"), {
ssr: false,
// Make sure to code a placeholder so the UI doesn't jump when the component loads
loading: () => ,
});export function Header() {
return (
My App
);
}
``- This discussion reply
- https://hangindev.com/blog/avoid-flash-of-default-theme-an-implementation-of-dark-mode-in-react-app