javascriptnext.jsnext.js13nextjs-dynamic-routing

Passing props to Layout for dynamic routes (App Router) in Next.js 13


I want to pass props to Layout for some dynamic routes. This is the project structure:

/app
-/(site)
--/layout.tsx
--/page.tsx
--/[slug]/page.tsx
--/[slug]/layout.tsx

in the site layout:

export default async function IndexRoute({
  children
}: {
  children: React.ReactNode
}) {
  const settings = await getSettings()

  const layout = (
    <html  lang='en'>
      <body>
        <div className='flex min-h-screen flex-col'>
          <a className='sr-only' href='#mainContent'>
            Skip to content
          </a>
          <Suspense>
            <Masthead />
          </Suspense>
          <main className='flex flex-1 flex-col ' id='mainContent'>
            <Suspense>{children}</Suspense>
          </main>
          <Suspense>
            <Foundation menus={settings.menus.footer} />
          </Suspense>
        </div>
      </body>
    </html>
  )
  return layout
}

Apparently this layout will consider the [slug] layout as a nested layout. My goal here is to create a layout for the [slug] routes so I can pass props to that layout. How can I solve this?


Solution

  • there is no communication between a page and a layout.

    page.tsx is rendered as the children component of the layout. From here

    Unlike Pages, Layout components do not receive the searchParams prop. This is because a shared layout is not re-rendered during navigation which could lead to stale searchParams between navigations.

    That is because a layout file serves as a template or structural framework that defines the overall structure, design, and arrangement of elements for multiple pages within a website or web application. It does not rerender so user always see the layout components on the browser even when they navigate to another page.