Menu
Coddy logo textTech

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/pizza

Visit /menu/pizza and Next.js nests them outside-in:

RootLayout
    MenuLayout
        PizzaPage

Visit / 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 icon

Challenge

Easy

The 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> with id="menu-header" and the text Menu

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>
    );
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Next.js Essentials