In Next.js, layouts are a way to wrap your pages with a common structure or design. They help to keep your code DRY (Don't Repeat Yourself) by providing a consistent layout across multiple pages. Here's a step-by-step guide on how to create and use layouts in Next.js:
Create a Layout Component:
Start by creating a layout component that represents the common structure you want to use across multiple pages. Create a new file for your layout component, for example, components/Layout.js
:
jsx// components/Layout.js
import React from 'react';
const Layout = ({ children }) => {
return (
<div>
<header>
{/* Your header content goes here */}
</header>
<main>{children}</main>
<footer>
{/* Your footer content goes here */}
</footer>
</div>
);
};
export default Layout;
Use the Layout Component in Pages:
In your pages, import and use the layout component. You can wrap the content of each page with the layout component. For example, in pages/index.js
:
jsx// pages/index.js
import React from 'react';
import Layout from '../components/Layout';
const Home = () => {
return (
<Layout>
<h1>Welcome to my Next.js site!</h1>
{/* Other page content goes here */}
</Layout>
);
};
export default Home;
Dynamic Layouts:
If you need different layouts for different pages, you can create multiple layout components and use them accordingly. For example, you might have a AdminLayout
for admin pages and a PublicLayout
for public pages.
Customizing Layouts:
You can pass props to your layout components to customize them based on specific pages. For example, you might pass a title
prop to set the page title dynamically.
jsx// components/Layout.js
import Head from 'next/head';
const Layout = ({ children, title = 'Next.js Site' }) => {
return (
<div>
<Head>
<title>{title}</title>
</Head>
<header>
{/* Your header content goes here */}
</header>
<main>{children}</main>
<footer>
{/* Your footer content goes here */}
</footer>
</div>
);
};
Then, in your pages:
jsx// pages/index.js
const Home = () => {
return (
<Layout title="Home Page">
<h1>Welcome to my Next.js site!</h1>
{/* Other page content goes here */}
</Layout>
);
};
Global Styles: You can also include global styles in your layout components, either by using global CSS files or CSS-in-JS libraries like styled-components.
jsx// components/Layout.js
import 'styles/global.css';
// rest of the component remains the same
Ensure that your global styles are imported in the layout to apply them across all pages.
That's it! With this setup, your pages will share a common layout, making it easier to maintain and update the overall structure of your site.