Customizing a Next.js app

17 September 2021

In this tutorial we’re going to use the default template we’ve installed and add a custom layout, header and footer each in separate files that can all be reused.

When the dev environment started up in the last tutorial we saw the default page that comes with the app. All the code for that page is located in the index.js file inside the pages folder. The index.js file is at the root of our web app.

Open the index.js file and delete everything in it. We’ll start from scratch and build our app so we understand exactly what’s going on.

In your index.js file enter the following code:

index.js
export default function Home() {
    return (
        <p>Welcome</p>
    )
}

Each page in Next.js is a React component so this will look familiar if you’ve used React before.

Start your dev environment again using npm run dev and load localhost:3000 in a browser. You should see a white page with Welcome in the top right corner. This is the simplest a page in Next.js can be but we’ll build up from here.

In the project root, create a folder called components. Within this folder we’ll create files that will make up each of the pages. Add a new file in the components directory named header.js and add the following code.

header.js
export default function Header() {
    return (
      <header>
          <h1>My App</h1>
      </header>
    )
}

This is a simple header component that returns a <header> element with an <h1> element inside it.

Create another new file in components called footer.js and add the following code to it:

footer.js
export default function Footer() {
    return (
     <footer>
         <p>Copyright My App</p>
     </footer>
    )
}

Finally, create a file called layout.js. This file will be the container for our header and footer components.

layout.js
import Header from "./header"
import Footer from "./footer"

export default function Layout(props) {
    return (
        <div>
            <Header/>
            {props.children}
            <Footer/>
        </div>
    )
}

At the top of layout.js we import the header and footer components and use them in the Layout component.

The other new thing here is the {props.children} which will include anything between the opening and closing tags of the Layout component whenever it is used.

Now we’ve got the 3 components set up, lets add the Layout component to our index.js page.

index.js
import Layout from "../components/layout";

export default function Home() {
    return (
      <Layout>
        <p>Welcome</p>
      </Layout>
    )
}

Now, when you start your dev environment and visit localhost:3000 in a browser, you should see the header, content, and footer we have added being displayed on the page. You have now created a basic structure for your app using custom components for the layout, header, and footer. All the parts are in place now for us to begin expanding each of our components and adding some styling.