Implémenter le dark mode avec Tailwindcss dans Next.js

npx create-next-app dark-mode
yarn add -D tailwindcss postcss postcss-preset-env
yarn add next-themes
module.exports = {
plugins: [
"tailwindcss",
[
"postcss-preset-env",
{
autoprefixer: {
flexbox: "no-2009",
},
stage: 3,
features: {
"custom-properties": false,
},
},
],
],
};
module.exports = {
future: {
removeDeprecatedGapUtilities: true,
purgeLayersByDefault: true,
},
darkMode: "class",
purge: ["./components/**/*.{js,ts,jsx,tsx}", "./pages/**/*.{js,ts,jsx,tsx}"],
theme: {},
variants: {},
};
import React from "react";
import Document, { Html, Head, Main, NextScript } from "next/document";

class MyDocument extends Document {
render() {
return (
<Html>
<Head />
<body className="bg-white text-black dark:bg-black dark:text-white">
<Main />
<NextScript />
</body>
</Html>
);
}
}

export default MyDocument;
@tailwind components;
@tailwind utilities;
import "../styles/globals.css";
import { ThemeProvider } from "next-themes";

function MyApp({ Component, pageProps }) {
return (
<ThemeProvider attribute="class">
<Component {...pageProps} />
</ThemeProvider>
);
}

export default MyApp;
import Head from "next/head";

export default function Home() {
return (
<div className="text-center">
<Head>
<title>Dark mode with Tailwind and Next.js</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<h1 className="text:2xl">Dark mode with Tailwind and Next-themes</h1>
</div>
);
}
yarn dev
import { useTheme } from "next-themes";
const { theme, setTheme } = useTheme();
const [isMounted, setIsMounted] = useState(false);
useEffect(() => {
setIsMounted(true);
}, []);
const switchTheme = () => {
if (isMounted) {
setTheme(theme === "light" ? "dark" : "light");
}
};
import { useEffect, useState } from "react";
import Head from "next/head";
import { useTheme } from "next-themes";
export default function Home() {
const [isMounted, setIsMounted] = useState(false);
const { theme, setTheme } = useTheme();
useEffect(() => {
setIsMounted(true);
}, []);
const switchTheme = () => {
if (isMounted) {
setTheme(theme === "light" ? "dark" : "light");
}
};
return (
<div className="text-center">
<Head>
<title>
Dark mode with Tailwind and Next.js
</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<h1 className="text:2xl">
Dark mode with Tailwind and Next- themes
</h1>
<button onClick={switchTheme}>Change theme</button>
</div>
);
}

--

--

Web Developer | Udemy Instructor | Creator of Salvia-kit & Kimia-ui

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Enoch Ndika

Enoch Ndika

Web Developer | Udemy Instructor | Creator of Salvia-kit & Kimia-ui