React's modular nature allows us to create reusable components, and layouts are no exception. In Next.js, there's a variety of ways to implement custom layouts. In this blog, we'll explore two of the most common approaches:
A Single Shared Layout in Next.js is a custom layout that serves as a blueprint for every page within our application. Consider a scenario where our application has a common structure, featuring a navbar and a footer that remain consistent across all pages. In such cases, we can define our layout like this:
To implement this custom layout, we can wrap the Component within our _app.tsx file:
One cool aspect of the Single Shared Layout is that it is consistently reused across all pages, which can also preserve the state of the layout.
If we want to have different layouts (ex. authentication, dashboard, etc...), we can define a getLayout property to pages that will receive the page in props, and wrap it in the layout that we want. Since getLayout is a function, we can have nested layouts if we want.
Here's an example of a page:
For this approach to work, we'll need to make a few adjustments to our _app.tsx:
It's worth noting that Custom Layouts aren't considered as pages. So, if we want to fetch data inside our layout, we'll need to do it on the client-side. we can still use getStaticProps and getServerSideProps in our pages, but not in our layouts.
That's how we can create custom layout in Next.js.