Next.js Layouts and Shared Components
Introduction
A Next.js application consists of several components that share a layout, such as the header, footer, and a navigation bar. In such cases, it becomes cumbersome to repeat these components across every page repeatedly. In addition, if the layout changes, it becomes painful to modify each page that uses it.
In Next.js, we can create layouts and shared components to solve this problem by using Higher-Order Components (HOCs). HOCs are functions that take an existing component and return a new component that wraps around it.
Syntax
import Layout from '/path/to/Layout'
export default function WrappedComponent() {
return (
<Layout>
{/* Child components */}
</Layout>
);
}
Example
// components/Layout.js
import Head from 'next/head'
import Header from './Header'
import Footer from './Footer'
export default function Layout({ children }) {
return (
<div>
<Head>
<title>My Next.js website</title>
</Head>
<Header />
{ children }
<Footer />
</div>
);
}
// pages/index.js
import Layout from '../components/Layout'
import React from 'react'
export default function Home() {
return (
<Layout>
<h1>Welcome to my website!</h1>
<p>This is my Next.js website demo.</p>
</Layout>
);
}
Output
The above example will output a basic website with a header, footer, and a welcome message on the homepage.
Explanation
In the above example, we have created a Layout component that includes a header, footer, and wraps the child components passed to it. We have also created a Home component that uses the Layout component. The Home
component passes its child components to the Layout
component using the children
prop.
Use
The Layout component can be used to wrap all components that share a common layout or any component you want to reuse across different pages. We can split the components into small, reusable components like a header, footer, and navigation bar, and assemble them using the Layout
component so that they can be shared across multiple pages of the application.
Important Points
- Creating a layout component is useful when there is a repeated layout across different pages in an application.
- HOC (Higher-Order Component) provides an easy way to create a reusable layout component in Next.js.
- A shared components folder can be created for commonly used components in the application.
Summary
Next.js provides an easy and efficient way to create layouts and shared components using Higher-Order Components. The Layout
component can be used to wrap components that share a common layout or any component that needs to be reused across different pages. With small, reusable components and smart composition, we can simplify our codebase and encourage consistency between pages.