3

I'm looking to achieve the results listed in this blog but with Next 13's new appDir. Flicker-free Dark Theme Toggle

My darkmode flickers on refresh.

// pages/_app no longer exist. How do you alter the < themeProvider > to match the new layout.tsx?

My files are listed below. Thank you for any knowledge.

Quick Setup

npx create-next-app@latest -D tailwindcss my-app

Next 13 Setup Documentation

https://beta.nextjs.org/docs/upgrade-guide

// app/layout.tsx

import Darkmode from './darkmode'
export default function RootLayout({
  children,
}:{
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <head></head>
      <body>
        <button className='h-8 w-8 p-1 bg-blue-300 dark:bg-red-600 rounded-full'>
          <Darkmode/>
        </button>
        {children}
      </body>
    </html>
  )
}

// app/darkmode.tsx

'use client'
import{useEffect, useState}from'react';

function Darkmode() {
  const[darkMode,setDarkMode]=useState(false);
  useEffect(()=>{
    if(localStorage.theme==='dark'||(!('theme'in localStorage)&&window.matchMedia('(prefers-color-scheme:dark)').matches)){
      document.documentElement.classList.add('dark')
      localStorage.theme='dark'
      setDarkMode(!darkMode)
    }else{
      document.documentElement.classList.remove('dark')
      localStorage.theme='light';
    }
  },[])

  const changeTheme=()=>{
    localStorage.theme=darkMode?'light':'dark'
    setDarkMode(!darkMode)
    if(darkMode){
      document.documentElement.classList.remove("dark");
    }else{
      document.documentElement.classList.add("dark");
    }
  };
  
  return (
    <div className='h-6 w-6' onClick={changeTheme}/>Dark</div>
  );
}

export default Darkmode;
dankswoops
  • 103
  • 7

1 Answers1

0

Lee over at vercel actually has a really cool way of doing this using tailwind in his blog example. I would recommend that pattern as it is much easier to maintain.

You can set a dark mode theme in your tailwind config and use the Nextjs ThemeProvider component to change it. Here is the code from Lee and the tailwind docs. Good luck.

Dax
  • 11
  • 2
  • 1
    Lee was using the pages structure in the commit you linked. He's migrated to the app directory since then, but no longer has theme toggling/ checking local storage anymore. The poster specifically states they're using the new next app directory. Here's a relevant issue for why it's difficult (hydration issues) https://github.com/pacocoursey/next-themes/issues/152 – shanshine Feb 12 '23 at 15:55
  • Ahhh My bad. Thanks for catching that. – Dax Feb 17 '23 at 15:08