The Layout File In NextJs

Qasim AminQasim Amin
2 min read

What Is Layout


Layout is a file convention in NextJs that allows coders like us to access or implement code through the file branch. An example could be to make a navbar that is only used in that file tree, so you would create a navbar in the layout folder, and it allows you to have a navbar on each of the pages in the file tree.


Example - Code - Setup


To start the setup, we are going to create a NextJs app by going into a terminal and typing npx create-next-app . If you are unsure or not confident in creating nextjs applications you can have a look at my blog which goes through the basics of creating a NextJs app.

When you have created your next app, we are going to clean up some code. The first thing we need to clean up is the Global css, take out all of the code except of the tailwindcss code if you have implemented that.

The next thing is in the App folder in the page, delete everything inside of it. Add div tags that have any text inside of them.


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

That is everything for the setup. To run the application, go to the terminal and type in npm run dev .


Writing Code - Using Layout


In the layout file, we are going to play around with the code. Inside of the layout page, you can add a div under the body tag inside of the return section. You can put any text but when you do you will see that the text will appear on the page.

We can also see that it works when we add more files to the tree branch.

Inside of the app folder, add a folder called products. Add page and inside of that page add a function and a div tag inside of the return section.

Now if we go back to the app page and add a link to the products page:

import Link from "next/link";

export default function Home() {
  return (
    <div>
      <h1>Hello World</h1>
      <Link href="/Products">Products</Link>
    </div>
  )
}

We can see that if we click on the products link in the app, that the layout code is still there.


Conclusion


In conclusion, this blog should have aided you in your progress into layouts in NextJs and should of taught you the basics of layouts.

0
Subscribe to my newsletter

Read articles from Qasim Amin directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Qasim Amin
Qasim Amin

I am a 13 year old coder