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
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