Open In App

How to add layout in Next.js ?

Last Updated : 06 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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

Project Structure: 

 

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. 

/pages/index.js




import React from 'react'
  
const HomePage = () => {
  return (
    <div>Hello Geeks!</div>
  )
}
  
export default HomePage


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.

/components/Layout.jsx




import React from "react";
  
const Header = () => {
  return <h3>This is Header</h3>;
};
  
const Footer = () => {
  return <h3>This is Footer</h3>;
};
  
const Layout = ({ children }) => {
  return (
    <>
      <Header />
      {children}
      <Footer />
    </>
  );
};
  
export default Layout;


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.

/pages/_app.js




import '../styles/globals.css'
import Layout from '../components/Layout'
  
function MyApp({ Component, pageProps }) {
  return (
    <Layout>
    <Component {...pageProps} />
    </Layout>
  )
}
  
export default MyApp


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.

/pages/test.jsx




import React from 'react'
  
const Test = () => {
  return (
    <div>This is a dummy page</div>
  )
}
  
export default Test


Step 7: Run your Next Application with the following command.

npm run dev

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads