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:
- Create a top-level directory called ‘components’ for storing the layout components
- For the layout shared by all pages, create a file called ‘Layout.js’
- 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:
- 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:
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:
- We create a new file for the page layout component. For example, we can create a file named 'AboutLayout.js'.
- Inside the file, define the layout component using React. For example:
3. 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:
In addition to page content, CSS can be used on layouts just as it is with pages (refer back to Styling section). Note that the {children} prop is used to pass the content of each page to the layout component to dynamically render page-specific content within the shared layout structure. By using layout components, we can avoid duplicating code for shared elements between pages.
Copyright © 2021 Code 4 Tomorrow. All rights reserved.
The code in this course is licensed under the MIT License.
If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.