Nested Layouts
Part of the Next.js Essentials section of Coddy's React journey — lesson 13 of 47.
The root layout isn't the only one. Drop a layout.jsx into any folder and it wraps that folder's routes, and only those.
app/
layout.jsx wraps EVERYTHING
page.jsx /
menu/
layout.jsx wraps /menu and everything under it
page.jsx /menu
pizza/
page.jsx /menu/pizzaVisit /menu/pizza and Next.js nests them outside-in:
RootLayout
MenuLayout
PizzaPageVisit / and only the root layout runs: the menu layout isn't in that URL's path, so it never appears.
A nested layout is written exactly like the root one, minus the shell: no <html>, no <body>. Just a component taking children.
This is how one section of a site gets its own sidebar, its own tabs, its own heading, without a single if statement about the current URL.
Challenge
EasyThe menu section needs its own heading: on /menu and its dish pages, but nowhere else.
app/menu/layout.jsx already exists and passes children straight through. Inside its <section>, above {children}, add:
- An
<h2>withid="menu-header"and the textMenu
The tests check the header shows on /menu and on /menu/pizza, and that it is gone back on /.
Try it yourself
import './globals.css';
export const metadata = {
title: 'My App',
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
{children}
</body>
</html>
);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Next.js Essentials
2Routing & Links
Folders Are RoutesNested RoutesLinking PagesDynamic RoutesNot Found PagesRecap: Routing3Layouts & Metadata
The Root LayoutShared NavigationNested LayoutsPage MetadataDynamic MetadataRecap: Layouts