Next.js Discord

Discord Forum

Dark mode in Nextjs14

Unanswered
Turkish Angora posted this in #help-forum
Open in Discord
Turkish AngoraOP
I need help creating a darkmode in my next js 14 website!

89 Replies

Turkish AngoraOP
in neext js 14 there is no app.jsx file though!
there is just app folder
you need to update in layout.tsx file
just this section is enough for you to implement dark-mode in next 14
Turkish AngoraOP
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={inter.className}>
<NextAuthProvider>
<Navbar2 />

{children}
<Footer />
</NextAuthProvider>
</body>
</html>
);
}

this is my existing code,
i have imported next theme
now where should i add themeprovider???
I will add it inside nextauth provider
to wrap navbar, children and footer
remember to add suppressHydrationWarning to html tag
Turkish AngoraOP
after lang="en"??
yeah
Turkish AngoraOP
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" suppressHydrationWarning>
<body className={inter.className}>
<NextAuthProvider>
<ThemeProvider>
<Navbar2 />

{children}
<Footer />
</ThemeProvider>
</NextAuthProvider>
</body>
</html>
);
}


is this enough?
exacly
https://github.com/pacocoursey/next-themes?tab=readme-ov-file#usetheme

here you will find theme change component to test it out ๐Ÿ™‚ remember to add 'use client' on top in next 14
also if you are using tailwind you need to change tailwind config to use class for darkmode, and add attribute with value class to provider <ThemeProvider attribute="class">
Turkish AngoraOP
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" suppressHydrationWarning>
<body className={inter.className}>
<NextAuthProvider>
<ThemeProvider attribute="class">
<Navbar2 />

{children}
<Footer />
</ThemeProvider>
</NextAuthProvider>
</body>
</html>
);
}


//tailwind.config

darkMode: "class",
theme: {
extend: {
now what should i do next?
i have already added themeswitcher component
what is the next step after these three
i am planning on using it with tailwind
exacly
Turkish AngoraOP
darkMode: "class",
theme: {
extend: {
colors: {
background: {
light: "#ffffff", // Light mode background color
dark: "#000000", // Dark mode background color
},
text: {
light: "#000000", // Light mode text color
dark: "#ffffff", // Dark mode text color
},
},



is this the way to define color variable??
now just check if it works ๐Ÿ˜„
Turkish AngoraOP
Unhandled Runtime Error
Error: Hydration failed because the initial UI does not match what was rendered on the server.

Warning: Expected server HTML to contain a matching text node for "system" in <div>.

See more info here: https://nextjs.org/docs/messages/react-hydration-error

1 of 3 errors
can you share project repository so I will be able to check that further?
Turkish AngoraOP
can i send you the code of this page??
layout one?
perfectly would be repository with whole project but for now layout, tailwind config and page should be ok
Turkish AngoraOP
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import Navbar from "./(components)/Navbar";
import Footer from "./(components)/Footer";
import { NextAuthProvider } from "./Providers";
import Navbar1 from "./(components)/Navbar1";
import Navbar2 from "./(components)/Navbar2";
import { ThemeProvider } from "next-themes";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
title: "Your Project Title",
description: "Your Project Description",
};

export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" suppressHydrationWarning>
<body className={inter.className}>
<NextAuthProvider>
<ThemeProvider attribute="class">
<Navbar2 />

{children}
<Footer />
</ThemeProvider>
</NextAuthProvider>
</body>
</html>
);
};
this is l;ayout.tsx
import type { Config } from "tailwindcss";

const config: Config = {
content: [
"./pages//*.{js,ts,jsx,tsx,mdx}",
"./components/
/.{js,ts,jsx,tsx,mdx}",
"./(components)/**/
.{js,ts,jsx,tsx,mdx}",
"./app/*/.{js,ts,jsx,tsx,mdx}",
],
darkMode: "class",
theme: {
extend: {
colors: {
background: {
light: "#ffffff", // Light mode background color
dark: "#000000", // Dark mode background color
},
text: {
light: "#000000", // Light mode text color
dark: "#ffffff", // Dark mode text color
},
},
backgroundImage: {
"gradient-radial": "radial-gradient(var(--tw-gradient-stops))",
"gradient-conic":
"conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",
},
},
},
plugins: [],
};

export default config;
tailwind config
try to re-run dev server and check again - everything is correct
albo please tell me - which nextjs version are you using?
Turkish AngoraOP
14
exacly which ๐Ÿ˜„
14.1.4, 14.2.2 etc
as there are some problems in latest nextjs with tailwind projects
Turkish AngoraOP
14.1.3
โ–ฒ Next.js 14.1.3
ok, perfect
so it's unaffected version
It should work as expected with that config. Please stop dev server, remove .next catalog (nextjs dev cache) and run it again
@Turkish Angora Unhandled Runtime Error Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected server HTML to contain a matching text node for "system" in <div>. See more info here: https://nextjs.org/docs/messages/react-hydration-error 1 of 3 errors
Quoting the link above:
Warning! The above code is hydration unsafe and will throw a hydration mismatch warning when rendering with SSG or SSR. This is because we cannot know the theme on the server, so it will always be undefined until mounted on the client.

You should delay rendering any theme toggling UI until mounted on the client. See the example.
That is the reason of your hydration error
Yeah @joulev, but it's suppressed ๐Ÿ˜„ It should occure but not be thorown.
Turkish AngoraOP
it is working, but now how should i use it in my website for color??

return (
#Unknown Channel
<p className=" ">duhfeudif</p>
ssssssssss <ThemeChanger />
</>
);

text, backgorund are defined but how should i use it to see the change?
@Z4NR34L Yeah <@484037068239142956>, but it's suppressed ๐Ÿ˜„ It should occure but not be thorown.
The suppress only happens for the html tag, not the dark/light mode selector. You have to completely hide that selector during server prerendering
@Z4NR34L just use tailwind `dark:` prefix
Turkish AngoraOP
can you add one example in the code i written?>
as this is not shown now, but if it will create problem in future i would like to sort it now
@Turkish Angora do i have to do this in my code???
I had checked now - you don't need when you have 'use client' on top. Works like that in all my projects without hydration issues
@Turkish Angora can you add one example in the code i written?>
dark:border-red-500 border-green-500 - that means that on dark mode the border would be red, on light mode green
Turkish AngoraOP
i mean if i have already made a variable in the tailwind config fiole, then cant i just use the variable, and it will automatically changed if toggled?
in case of your config, bg-background will change itself according to current theme
@Z4NR34L I had checked now - you don't need when you have 'use client' on top. Works like that in all my projects without hydration issues
Turkish AngoraOP
i didnt use use client, as that wouldf caused problem, since it doensot allow to write meta tag and description
but if you want to use tailwind built-in props you need to prefix it with dark:
Turkish AngoraOP
which might be the best practise?
@Turkish Angora i didnt use use client, as that wouldf caused problem, since it doensot allow to write meta tag and description
I didn't told that you have to. You need to use 'use client' for components using client-side APIs like React Contexts, hooks
Turkish AngoraOP
Unhandled Runtime Error
Error: Hydration failed because the initial UI does not match what was rendered on the server.

Warning: Expected server HTML to contain a matching text node for "system" in <div>.

See more info here: https://nextjs.org/docs/messages/react-hydration-error

Component Stack


again after sometiime this error is showm!!!
@Turkish Angora which might be the best practise?
The most commonly met is mixing of both. We are making own variabled for design system colors (background, foregrounds, brands etc), and use tailwind built-in props like text-red-500 but with prefixes to adjust color pallete to theme
Turkish AngoraOP
"use client";
import { useTheme } from "next-themes";

export const ThemeChanger = () => {
const { theme, setTheme } = useTheme();

return (
<div>
The current theme is: {theme}
<button onClick={() => setTheme("light")}>Light Mode</button>
<button onClick={() => setTheme("dark")}>Dark Mode</button>
</div>
);
};
ok, there you placed that component? ๐Ÿ˜„
Better add dynamic import for that component:

const ThemeToggle = dynamic(() => import("@/components/theme-toggle"), {
    ssr: false,
  })


Change component path and names according to your code, it's just example
Turkish AngoraOP
import React from "react";
import { ThemeChanger } from "../(components)/tms";
const page2 = () => {
return (
#Unknown Channel
<p className="dark:border-red-500 border-green-500 ">duhfeudif</p>
ssssssssss <ThemeChanger />
</>
);
};

export default page2;
it is called from here
where you import theme changer component
Turkish AngoraOP
page 2
const ThemeChanger = dynamic(() => import("../(components)/tms"), {
    ssr: false,
  })


You should use something like that in that case
Turkish AngoraOP
Cannot find name 'dynamic'.ts(2304)
import it from next/dynamic as it is made in docs that I've linked:

https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading#nextdynamic
Turkish AngoraOP
Unhandled Runtime Error
Error: Unsupported Server Component type: undefined
Can you share current code when you're expecting errors? That would simplify cooperation ๐Ÿ˜„
Multiflora rose seed chalcid
I am interested @Turkish Angora
Turkish AngoraOP
I can't share the code
Is there any other way???
Other methods to do this
Or something like that?
fixing code needs to see code - it's hord to make this well and fast. You can always prepare minimum reproduction repository of this problem and share that repository with us.

https://nextjs-faq.com/minimal-reproduction-repository