While we haven’t fully covered the topic of pages and routing, let’s take a moment to explore layouts, a core feature of Next.js 15.
According to the documentation, a layout is the UI shared across multiple pages. Layouts allow you to define consistent elements like headers, navigation menus, or footers that persist across your application. Let’s break this down step by step.
A layout in Next.js is simply a React component exported by default from a file named layout.js
. If you’ve set up your Next.js project as outlined previously, you should already have a layout.js
file in the app
folder.
children
PropThe layout component should accept a children
prop. This prop represents the content of any page wrapped by the layout.
If you’ve used children
in React before, you’ll find this familiar. Let’s see how it works in practice.
children
in ReactLet’s revisit how the children
prop functions. For example, in a React component like Card
:
<Card>
This content is passed as children.
</Card>
The Card
component receives the children
prop and renders whatever content is passed within its opening and closing tags.
layout.js
File in Next.js 15The root layout file, located in the app
directory, is required in every Next.js application.
It must include the basic <html>
and <body>
tags.
Example root layout:
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<main>{children}</main>
</body>
</html>
);
}
Let’s enhance the layout with a header to demonstrate how shared UI works:
Open the layout.js
file and modify it like this:
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header className="p-4 border border-yellow-500">
I am visible on all pages
</header>
<main>{children}</main>
</body>
</html>
);
}
Navigate to your home page: the header appears at the top.
Go to another page (e.g., /about
or /projects
): the same header persists.
Layouts in Next.js 15 simplify the process of creating consistent interfaces. For instance, you can use them to:
Display a navigation menu or footer on all pages.
Manage common UI patterns without duplicating code.
Additionally, you can create nested layouts for more complex applications, where different sections of your app have their own specific layouts.
Layouts are a powerful feature in Next.js 15 that let you create shared UI components, improving both maintainability and consistency across your application. In the next steps, explore more advanced concepts like nested layouts or dynamic content to make the most out of this feature. 🚀