Layouts

Deconstructing a page means picking it apart and creating separate components. These component can then be reused between several pages and layouts. There are two types of common layouts.

Single Shared Layouts

If you have one layout for your entire application, you can create a custom app and wrap your application in the layout.

The <Layout /> component is re-used when changing pages, so its component state will be preserved.

Example:

// pages/_app.js
import Layout from '../components/layout'

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

Per-Page Layouts

You can also add a property getLayout to your page if you need multiple layouts. This allows you to return a React component for the layout.

You can then define the layout on a per-page basis.

Example:

// pages/index.js
import Layout from '../components/layout'
import NestedLayout from '../components/nested-layout'

export default function Page() {
  return {
    /** your content */
  }
}

Page.getLayout = function getLayout(page) {
  return (
    <Layout>
      <NestedLayout>
        {page}
      </NestedLayout>
    </Layout>)}
  
// pages/_app.js
export default function MyApp({ Component, pageProps }) {
  // use the layout defined at the page level if it is available
  const getLayout = Component.getLayout || ((page) => page)
  return getLayout(
    <Component {...pageProps} />
  )
}

The above layout pattern makes sure that the page state remains the same, so input values, scroll positions etc. do not change all of a sudden.

External sources

Next.js Documentation about Layouts