With the React model, we can break down a webpage into multiple components that make up its layout. These components can be reused across different pages. For example, we might want the same top heading on each page.

When we use the same <layout /> component on multiple pages of the app, React treats it as a shared component instance rather than creating a new instance each time we switch pages. In other words, its state is maintained and users don't lose data when moving between pages.

Single Layout

To create a single layout shared by all pages in the app, we can do the following:

  1. Create a top-level directory called ‘components’ for storing the layout components
  2. For the layout shared by all pages, create a file called ‘Layout.js’
  3. In Layout.js, define the component layout using React. This component will contain the common elements shared by all pages, such as headers, footers, and navigation. For example, a basic layout component structure is shown below:

Untitled

  1. In our Next.js pages in which we want to share the layout, import and wrap the content of each page with the layout component. For example, to use the layout in our home page, we can use the following code:

Untitled

Per-page layouts

You can add practice problems here if you want. Follow the format below.

Per-page layouts refer to creating different layout components to wrap around specific pages. By using the ‘getLayout’ property, we can specify a React component for the layout, customizing it to each page. Because the layout is returned through a function, it enables nesting layouts at the per-page level.

We can create a per-page layout with the following steps:

  1. We create a new file for the page layout component. For example, we can create a file named 'AboutLayout.js'.
  2. Inside the file, define the layout component using React. For example:

Untitled

  1. In the corresponding page component the layout component will be applied to, import the layout component and use it to wrap the content of the page component. For example, importing the AboutLayout component into the about.js page:

Untitled