Layouts in Next.js allow you to define a common structure for your pages. They can be used to wrap your pages, add common elements, and provide a consistent look and feel across your application.
The root or global layout is defined in the app
directory.
This layout is applied to all pages in your application, providing a consistent structure.
- Common Structure: Wraps your pages with elements like headers and footers.
- Consistency: Ensures a uniform look and feel across your application.
If you delete the root layout file and visit a page, Next.js will regenerate it with the default layout structure.
In this example, we import a stylesheet to include Tailwind CSS and wrap the child component, which injects the page.js
/page.tsx
content, with a styled header and footer.
// app/layout.tsx
import '../styles/globals.css'; // Import Tailwind CSS or any global styles
export const metadata = {
title: 'Next.js',
description: 'Generated by Next.js',
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang='en'>
<body>
<header className='bg-slate-900 text-white'>
<h1 className='text-3xl font-bold'>Header</h1>
</header>
{children}
<footer className='bg-slate-900 text-white'>
<h3 className='text-2xl font-bold'>Footer</h3>
</footer>
</body>
</html>
);
}
- Import Stylesheet: The
globals.css
file is imported to apply Tailwind CSS styles. - Metadata: The
metadata
object defines the title and description for the application. - Header and Footer: The layout includes a styled header and footer, using Tailwind CSS classes for styling, and wraps the
children
prop, which represents the content of thepage.js
/page.tsx
files.
By using layouts, you can efficiently manage the overall structure of your application, ensuring that common elements are consistently applied across all pages.