skip to Main Content

I am unable to render layout.tsx with a default theme as the theme provider is needed and useContext is called. Therefore next js complains about not being able to run server-side. So I put the use client field into the document, and now the metadata tags won’t load.

layout.tsx

'use client'

import { Metadata } from 'next'
export const metadata: Metadata = {
  title: {
    default: 'some title',
    template: '%s | some title'
  }
}

import { createTheme, ThemeProvider } from '@mui/material/styles'
const theme = createTheme({...

export default ({children}: {children: React.ReactNode}) => (

    <ThemeProvider theme={theme}>
        <LocalizationProvider dateAdapter={AdapterDayjs}>
            <html>
                <body>{children}</body>
            </html>
        </LocalizationProvider>
    </ThemeProvider>
)

2

Answers


  1. Do not make your layout a client component, rather create a client component called Provider that then can be imported in your layout. Heres an example:

    "use client";
    
    import { createTheme, ThemeProvider } from '@mui/material/styles'
    
    interface Props extends React.PropsWithChildren {}
    
    const theme = createTheme(/* ... */);
    
    export default function Provider({ children }: Props) {
      return <ThemeProvider>{ children }</ThemeProvider>;
    }
    
    Login or Signup to reply.
  2. You need to split them in 2 files simple, one client & another server

    Layout.tsx

    import { Metadata } from 'next'
    
    import RootLayout from './RootLayout'
    
    export const metadata: Metadata = {
      title: {
        default: 'some title',
        template: '%s | some title'
      }
    }
    
    export default function Layout({ children }: LayoutProps) {
        return (
            <html lang="en">
                <body>
                    <RootLayout>{children}</RootLayout>
                </body>
            </html>
        )
    }
    

    RootLayout.tsx

    'use client'
    
    import { createTheme, ThemeProvider } from '@mui/material/styles'
    const theme = createTheme({})
    
    export default RootLayout({children}: {children: React.ReactNode}) => (
    
        <ThemeProvider theme={theme}>
            <LocalizationProvider dateAdapter={AdapterDayjs}>
                <html>
                    <body>{children}</body>
                </html>
            </LocalizationProvider>
        </ThemeProvider>
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search