Skip to main content

Using Layouts

You can use layouts to provide a consistent look and feel to your pages. Layouts are React components that wrap around your page content. There are two ways to use layouts:

  • Applying a layout with a pages/_app.js file
  • Applying layouts to individual pages using a getLayout function

We'll fist look at applying a layout using a pages/_app.js file.

The starting point is to create a layout component. To create a layout component, create a file named components/layout.js. Then, add the following code:

// components/layout.js

export default function Layout({ children }) {
return (
<>
<h1>My Next.js App</h1>
<hr/>
<main>{children}</main>
</>
)
}

Next, we'll create a pages/_app.js file in the pages directory. Then, we'll add the following code to the pages/_app.js file:

// pages/_app.js

import Layout from '../components/layout'

export default function MyApp({ Component, pageProps }) {
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
}

In this example, we're using the Layout component to wrap around the Component that's passed in. This will use the same layout for all of our pages. But, we can also specify a different layout for each page.

Applying Layouts to Individual Pages

To apply a layout to a specific page, we can use the getLayout function. The getLayout function is a function that takes in a page object and returns a layout component. Here's an example of a getLayout function:

// pages/index.js

import Layout from '../components/layout'

export default () => (
<h1>Hello World</h1>
);

Page.getLayout = function getLayout(page) {
return (
<Layout>
{page}
</Layout>
)
}