Search code examples
reactjsnext.jsserver-side-renderingnext.js13

Pass props to page.jsx child from root layout (next.js 13)


How do you pass props to the the page.jsx of layout? (NEXT 13)

//app/blog/layout.jsx

export default function RootLayout({ children }) {
  return (
    <div>
      <Navbar />
      <Sidebar />
      {/*How do I pass any props from this root layout to this {children} that Im getting from page.jsx*/}
      {children}
    </div>
  );
}

Basically, How do you pass a prop to a function prop (Next. JS 13)?


Solution

  • According to the next13 docs you cannot:

    It's not possible to pass data between a parent layout and its children. However, you can fetch the same data in a route more than once, and React will automatically dedupe the requests without affecting performance.

    Because the layout component refers to a component that defines the overall structure and arrangement of other components within an application or a specific section of the UI. it is not designed to implement state management. its whole purpose is to reduce the time to first render to increase the user experience

    But I found a way. In Rootlayout, console.log(props)

    export default function RootLayout(props) {
      console.log("props in layout",props)
      return (
            <div>
              {props.children}
            </div>
      );}
    

    this is what you will see

    props in layout {
      children: {
        '$$typeof': Symbol(react.element),
        type: {
          '$$typeof': Symbol(react.module.reference),
          filepath: '/home/tesla//node_modules/next/dist/client/components/layout-router.js',
          name: '',
          async: false
        },
        key: null,
        ref: null,
        props: {
          parallelRouterKey: 'children',
          segmentPath: [Array],
          error: undefined,
          errorStyles: undefined,
          loading: undefined,
          loadingStyles: undefined,
          hasLoading: false,
          template: [Object],
          templateStyles: undefined,
          notFound: [Object],
          notFoundStyles: undefined,
          childProp: [Object],
          rootLayoutIncluded: true
        },
        _owner: null,
        _store: {}
      },
      // THIS IS HOW WE PASS PROPS
      params: {}
    }
    

    Many properties are not extensible but params. we can dynamically add properties to this object. for example

         props.params.newProp = "testing";
    

    Now visit page.js and

    const Page = (props) => {
      console.log("props in page", props);
      return ()}
    

    you will see that props is added to the params object

    enter image description here

    No matter what I tried, page.tsx had only two props: params and searchParams. searchParams is automatically populated if you have query parameters on url. So, I think params are the only way to pass props from the root layout. you can pass functions too