Navigate Between Pages

Link Component

When linking between pages on websites, you use the <a> HTML tag.

In Next.js, you use the Link Component from next/link to wrap the <a> tag. <Link> allows you to do client-side navigation to a different page in the application.

Using <Link>

First, open pages/index.js, and import the Link component from next/link by adding this line at the top:

import Link from 'next/link'

Then find the h1 tag that looks like this:

<h1 className="title">
  Learn <a href="https://nextjs.org">Next.js!</a>
</h1>

And change it to:

<h1 className="title">
  Read{' '}
  <Link href="/posts/first-post">
    <a>this page!</a>
  </Link>
</h1>

{' '} adds an empty space, which is used to divide text over multiple lines.

Next, open pages/posts/first-post.js and replace its content with the following:

import Link from 'next/link'

export default function FirstPost() {
  return (
    <>
      <h1>First Post</h1>
      <h2>
        <Link href="/">
          <a>Back to home</a>
        </Link>
      </h2>
    </>
  )
}

As you can see, the Link component is similar to using <a> tags, but instead of <a href="…">, you use <Link href="…"> and put an <a> tag inside.

Let’s check to see if it works. You should now have a link on each page, allowing you to go back and forth: