4 min read
ā¢Question 5 of 47easyHow do layouts work in Next.js?
Creating shared layouts with the App Router.
What You'll Learn
- Root layout
- Nested layouts
- Layout patterns
Root Layout
code.txtTSX
// app/layout.tsx (required)
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<header>My App</header>
<main>{children}</main>
<footer>Ā© 2024</footer>
</body>
</html>
);
}Nested Layouts
code.txtTSX
// app/dashboard/layout.tsx
export default function DashboardLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className="dashboard">
<aside>Sidebar</aside>
<section>{children}</section>
</div>
);
}
// app/dashboard/page.tsx uses this layout
// app/dashboard/settings/page.tsx also uses itMultiple Root Layouts
code.jsJavaScript
app/
āāā (marketing)/
ā āāā layout.tsx ā Marketing layout
ā āāā page.tsx
āāā (app)/
āāā layout.tsx ā App layout
āāā dashboard/
āāā page.tsxLayout with Metadata
code.txtTSX
import { Metadata } from 'next';
export const metadata: Metadata = {
title: 'Dashboard',
description: 'User dashboard',
};
export default function Layout({ children }) {
return <div>{children}</div>;
}