Q24: How do you implement persistent Page-Level Layouts in the Pages Router?
Attach a custom .getLayout function property to individual page components. In pages/_app.js, execute Component.getLayout() to wrap active pages without unmounting shared layouts during navigation.
Page-Level Layout Setup
// pages/dashboard.js
export default function Dashboard() { return <h1>Dashboard</h1>; }
Dashboard.getLayout = function getLayout(page) {
return <SidebarLayout>{page}</SidebarLayout>;
};
// pages/_app.js
export default function MyApp({ Component, pageProps }) {
const getLayout = Component.getLayout || ((page) => page);
return getLayout(<Component {...pageProps} />);
}_app.js executes the page's getLayout function to maintain layout tree persistence.
Key Takeaways
Attaches custom
.getLayoutproperties to page component functions.Preserves component state and scroll position across page transitions.
Knowledge Check
What advantage does the getLayout pattern offer over wrapping page JSX directly in a layout component inside each file?