layout.tsx
takes a React component
as a children
. There is a default layout
file in the app
directory. The file determines the main layout of Header, Footer, and other
general component
. The layout
file in the app
directory can not be removed. It means if you delete the file and run the project, the layout
file will be regenerated.
layout
file may look like:
// app/layout.tsx
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<header>My App Header</header>
<main>{children}</main>
<footer>My App Footer</footer>
</body>
</html>
);
}
With the superpower of Next.js
, layout
receives all the files named page.tsx/jsx/...
and creates UI for you. Next.js
automatically wraps all page.tsx (or .js/.jsx/.tsx)
files under app/
with the nearest layout.tsx
in the file tree. You don’t manually import
or attach pages
to layouts—file-system conventions
, do that for you.
Nested layout
In your project, you need one shared layout
and another for deeper. Like, for root layout
app/layout.tsx
and for nested app/user/username/layout.tsx
.
The folder structure should look like this,
next-practice/app/
├── globals.css
├── layout.tsx
├── page.tsx
└── user/
├── page.tsx
└── username/
├── layout.tsx
└── page.tsx
How's it working?
* root layout app/layout.tsx
- It renders all children until it finds another
layout.tsx
file. In our case, the rootlayout
will render theapp/page.tsx
anduser/page.tsx
as they are the children oflayout.tsx
. - As
app/user/username/layout.tsx
contains anotherlayout
file, it will stop rendering the rootlayout
. - At this point,
app/user/username/layout.tsx
will render the new layout'sUI
, how you designed. - Now
app/user/username/layout.tsx
becomes the root layout for its nestedpages/routes
. - If you create more nested directories and
page.tsx
in theusername
, they will be rendered in theapp/user/username/layout.tsx
layout.
Keeping the page.tsx
in the same directory as layout.tsx
is a must. Otherwise, the route segment
for the layout will not be accessible. Keep in mind layout.tsx
does not create route
, but page.tsx
does. So to make the route
accessible, you need the page.tsx
there. For example
next-practice/app/
├── globals.css
├── layout.tsx
└── user/
├── page.tsx
└── username/
├── layout.tsx
- If you try to access
/user/username
you will see404 Not Found Page
. As there is nopage.tsx
file. To make theroute
accessible add apage.tsx/js/jsx/...
file there.