Next.js navigation

20 November 2021

Now that we’ve added some pages to our Next.js app, we can add a navigation bar to our header so we can easily access the pages. The navigation bar will be persistent across all pages and posts on our site.

This is what the structure of our pages looks like after the last post.

/pages
    /api
        hello.js
    /about
        history.js
        index.js
        our-team.js
    _app.js
    index.js

To create the links we’re going to use the built-in Link component from Next.js which is used in place of an <a> tag. Using the Link component has a few advantages including Next.js prefetching pages behind links that are in the viewport by default to make load times faster.

In our header.js file we’ll add an import to the Link component from Next.js so that we can make use of it.

Then we’ll add a new navigation container with an unordered list and a list item for each link we want. Inside the list of items we have a <Link> component with a href parameter with the route to the relevant page.

header.js
import styles from '../styles/Header.module.css';
import Link from 'next/link';

export default function Header() {
    return (
      <header>
          <div className={styles.container}>
            <div id={styles.site_title}>My App</div>
            <nav>
            <ul className={styles.navigation}>
              <li className={styles.items}><Link href="/">Home</Link></li>
              <li className={styles.items}><Link href="/about">About</Link></li>
              <li className={styles.items}><Link href="/about/history">History</Link></li>
              <li className={styles.items}><Link href="/about/our-team">Team</Link></li>
            </ul>
          </nav>
          </div>
      </header>
    )
}

The menu also needs a bit of styling so we’ll update the Header.module.css file to make the navigation menu a bit more presentable.

Header.module.css
.container {
    display: flex;
    justify-content: space-between;
    padding: 0 0.5rem;
    max-width: 80rem;
    margin: auto;
}

#site_title {
    font-size: 3rem;
    color: white;
    display: flex;
}

.navigation {
    list-style: none;
}

.items {
    float: left;
    padding-left: 2rem;
}

.items:hover {
    text-decoration: underline;
}

The link component will be used in our app for any and all types of links to any page, internal or external. The Next.js documentation contains the full information you need for the Link component.