Next.js Discord

Discord Forum

help: create MUI dark mode toggle in next.js 14 (with App Router)

Answered
Yellowstripe scad posted this in #help-forum
Open in Discord
Yellowstripe scadOP
hi all!
im tring to put a material ui dark mode toggle i want to build a simple comonent that will wrap all the app.
im tring to use the MUI toggle guide - https://mui.com/material-ui/customization/dark-mode/#toggling-color-mode
but since the old _app/_document folders are now in layout file that can not use client in it im having a bit of problem implementing the toggle component...
does someone have any idea how can i implement is without the hooks or with additional trick?
Thanks in advance!
Answered by Yellowstripe scad
dit it previously but this is the solution:
View full answer

10 Replies

Pollock
create a client component from the theme provider and use it in the layout
@Pollock create a client component from the theme provider and use it in the layout
Yellowstripe scadOP
first, thanks for your answer. i did it but when i click the button only the components are changing and the background remains the same color, in addition when im refreshing i get back to the default "light" mode.
it seems like on the button click only the client components re-render and the background (simple white) is still the same.
the toggler component is as the same as the Mui one with all its hooks.
Pollock
I'm not really sure how the mui works on that front. I'm using this lib: https://www.npmjs.com/package/next-themes
and it needed to create a client wrapper for the provider:
'use client';

import { ThemeProvider as NextThemesProvider } from 'next-themes';
import { type ThemeProviderProps } from 'next-themes/dist/types';

export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
  return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
}
and in layout wrap the childs with it:
<body>
        <ThemeProvider attribute="class" defaultTheme="system" enableSystem>
          <div>{children}</div>
        </ThemeProvider>
      </body>
and the darkmode toggle is another client component that calls:
onClick={() => setTheme('light')}
or an appropriate mode
Yellowstripe scadOP
dit it previously but this is the solution:
Answer
Yellowstripe scadOP
@Pollock i am really greatfull for all your help! u r awsome! thanks alot!
Highlander
@Yellowstripe scad Hi, I´m learning can you share the basic code or givme an newie explanation? I don´t know what i need to do in layout.tsx or pagetsx Thanks in advance