April 18, 2024
Next.js Using Layouts to Wrap Sub-Routes (or Nested Routes) Is an Effective Way
How to use Next.js layouts to wrap sub-routes for consistent structure and style across your application components.
Overview
In Next.js, using layouts to wrap sub-routes (or nested routes) is an effective way to apply consistent structure and style across application components. This requires some manual implementation rather than native framework support in the Pages Router.
Step 1: Layout Component Creation
Create a MainLayout.js component that wraps content with Header, Footer, and a dynamic children section for rendering sub-components:
function MainLayout({ children }) {
return (
<div>
<Header />
<main>{children}</main>
<Footer />
</div>
);
}
Step 2: Page Component Integration
Apply the layout to individual pages by wrapping page content within the layout component. For example, a profile page:
function ProfilePage() {
return (
<MainLayout>
<h1>Profile</h1>
<p>User profile content here</p>
</MainLayout>
);
}
Step 3: Nested Routes Strategy
Organize nested routes under subdirectories like pages/user/settings/ and apply layouts consistently across multiple sub-pages within those directories.
Global Layout Implementation
Use _app.js to implement application-wide layouts with conditional logic enabling different layouts for different route sections:
function MyApp({ Component, pageProps }) {
const getLayout = Component.getLayout || ((page) => (
<MainLayout>{page}</MainLayout>
));
return getLayout(<Component {...pageProps} />);
}
Per-Page Layout Specification
The getLayout pattern allows each page to specify its own layout while maintaining a default:
ProfilePage.getLayout = function getLayout(page) {
return <DashboardLayout>{page}</DashboardLayout>;
};
This approach provides maximum flexibility while keeping your codebase organized and DRY.
Written by Shyam Achuthan