Introduction to Next.js Layouts

Layouts in Next.js are an essential part of building a consistent and reusable user interface. They allow you to create a common structure for your pages, such as headers, footers, navigation menus, and more. In this tutorial, we'll learn how to create layouts in Next.js.


Creating a Layout Component

1. Start by creating a new JavaScript file for your layout component. For example, let's create a file named Layout.js:


// components/Layout.js
import React from 'react';
function Layout({ children }) {
return (
<div>
<header>
<h1>My App</h1>
</header>
<main>{children}</main>
<footer>
<p>© 2023 My App</p>
</footer>
</div>
);
}
export default Layout;

In this layout component, we've defined a common structure with a header, main content area, and footer.


Using the Layout Component

2. In your individual pages, you can use the layout component to wrap your content. For example:


// pages/index.js
import Layout from '../components/Layout';
function HomePage() {
return (
<Layout>
<h2>Welcome to the Home Page</h2>
<p>This is the home page content.</p>
</Layout>
);
}
export default HomePage;

By wrapping your content in the layout component, you ensure that the common UI structure is applied to each page.