How to add layout in Next.js ?
Next.js is a React-based full-stack framework developed by vercel that enables functionalities like pre-rendering of web pages. Unlike traditional react app where the entire app is loaded on the client, Next.js allow the web page to be rendered on the server, which is great for performance and SEO. You can learn more about Next.js here.
Layout Component: Layout components are used for sections of your site that you want to share across multiple pages like Navbar, Footer, etc. We can also manage the initial state of our Next application through this component as it is loaded on every page and wraps the top-level app container.
How to create a Layout Component?
Step 1: Create a new Next.js application using the below command:
npx create-next-app gfg
We’ll build a simple application layout with a navbar and footer and see how our Layout component appears on all pages.
Step 2: We’ll first cleanup the index.js file by deleting all the boilerplate code.
Step 3: Create a new folder in the root directory called components , and in that folder create a new file called Layout.jsx.
Step 4: In our Layout File, we can now add the Navbar and Footer components. We will create sub-components of Navbar and Footer. You can create separate files for these components, but we will create them in the same file for simplicity. The layout will accept one default prop called children, which will contain the contents wrapped between the Layout component.
Step 5: Import a Layout component in the /pages/_app.js file and wrap the top level Component, this component is passed as children to the Layout component.
Step 6: We can create a dummy page to make sure that our layout component is visible on all the pages. Create a new file inside the pages directory called test.jsx.
Step 7: Run your Next Application with the following command.
npm run dev
Please Login to comment...