Create Layout Components in Next JS

In this blog post, we will learn to create a layout in the next js.

Basically, the layout is an essential part of any application. Creating any application without a layout is a difficult task.

We need pages like the navbar and footer which are on every page of the application.
Without layout, we have to copy the same code on every page. In such a situation, we should create a layout.

So let’s start

Step 1: Create a new Next Application

To create a project, run:

If you already have the project then you can skip this step

npx create-next-app myapp
# or
yarn create next-app myapp

After creating a project run this command to move on the project directory.

cd myapp

Now. Run the project with this command, run:

npm run dev

Step 2: Create a “components” folder and components pages

Create a new folder at the root of the project. named “components”.

Under components, the folder creates three files.

components\Layout.js

import Navbar  from '../components/Navbar'
import Footer  from '../components/Footer'
export default function Layout({children}) {
  return (
    <>
        <Navbar/>
        <main>{children}</main>
        <Footer/>
    </>
  )
}

components\Navbar.js

import Link from 'next/link'
export default function Navbar() {
    return (
      <>
          <ul>
              <li> <Link href="/"><a>Home</a></Link> </li>
              <li> <Link href="/about"><a>About</a></Link> </li>
              <li> <Link href="/contact"><a>Contact</a></Link> </li>
          </ul>
      </>
    )
  }
  

components\Footer.js

export default function About() {
    return (
      <>
        <center>
            <div>
            <p>Footer Page</p>
            </div>
        </center>
      </>
    )
  }
  

Step 3: Edit _app.js file

Now we have to update our _app.js file. Just copy this code

pages\_app.js

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

export default MyApp

Step 4: Create and update some pages

Now we have to create some pages such as About and contact.

pages\index.js

export default function Home() {
  return (
    <div>
      <h1>Home Page</h1>
    </div>
  )
}

pages\about.js

export default function About() {
  return (
    <div>
      <h1>About Page</h1>
    </div>
  )
}

pages\contact.js

export default function Contact() {
    return (
      <div>
        <h1>Contact Page</h1>
      </div>
    )
  }
  
create-layout-in-nextjs
Visit to http://localhost:3000 to view your application.