Nested layouts
Layouts are UI components shared between multiple pages in your application. While every Next.js application requires a root layout (layout.tsx
in the app folder), you can also create nested layouts for specific sections of your application.
Creating nested layouts
To create a nested layout, add a layout.tsx
file in any folder within your app directory. Here’s an example of a nested layout for a product details page:
Directoryapp/
Directoryproducts/
- layout.tsx Nested layout
Directory[id]/
- page.tsx
/products/[id]
- page.tsx
- layout.tsx Root layout
- page.tsx
/
Here’s a basic product details layout component:
export default function ProductLayout({ children,}: { children: React.ReactNode;}) { return ( <div className="product-container"> {/* Main product info will be rendered via children */} <main className="product-main">{children}</main>
{/* Shared sections across all product pages */} <section className="similar-products"> <h2>Similar Products</h2> {/* Similar products component */} </section>
<section className="product-reviews"> <h2>Customer Reviews</h2> {/* Reviews component */} </section>
<section className="product-recommendations"> <h2>Frequently Bought Together</h2> {/* Recommendations component */} </section> </div> );}
The nested layout component accepts a children
prop that represents the content of the product ID page. Other sections are shared across all product pages.
How nested layouts work
Next.js processes layouts in the following order:
- Renders the root layout (
app/layout.tsx
) - Processes any nested layouts in the route hierarchy
- Renders the page content corresponding to the current route
For example, when visiting /products/iphone-16
:
- The root layout is rendered first
- The product layout is processed next
- The product ID page content is rendered inside the root layout and product layout
Use cases
Nested layouts are particularly useful for:
- Adding section-specific navigation
- Displaying related content
- Creating specialized interfaces for different parts of your application