Pages in Nextjs don't come with a hierarchy (like e.g. https://reactrouter.com/). If you want to render 2 pages with a shared layout, this layout must

abergenw / next-page-layout Public

submited by
Style Pass
2021-12-06 21:30:09

Pages in Nextjs don't come with a hierarchy (like e.g. https://reactrouter.com/). If you want to render 2 pages with a shared layout, this layout must be rendered individually by both pages. By default this means that the shared layout will remount whenever navigating between the pages (as the top-level page component changes). This has been a recurring topic in the community and was recently addressed by Nextjs when they introduced layouts.

Here we create (and export) a layout rendering a title using data fetched with getInitialProps. When server-side rendering, getInitialProps will run on the server similarly to how it would if this was a regular Nextjs page.

The page above defines its own getInitialProps but we don't have to call getInitialProps on the layout explicitly since the library takes care of this. In useLayoutProps we have the option to pass props to our layout (such as an overridden title). This is all type safe thanks to Typescript and type inference 👍

Above we create a child layout to our earlier Layout. We'd render a page with this layout just like we rendered the page with the parent Layout. getInitialProps, useLayoutProps and type inference still work out of the box 👍

Leave a Comment
Related Posts