When linking between pages on websites you generally 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.
<Link>
First, in pages/index.js
, import the Link
component from next/link
by adding this line at the top:
import Link from 'next/link'
Then modify this line in the h1
tag:
Learn <a href="https://nextjs.org">Next.js!</a>
To this:
Read <Link href="/posts/first-post"><a>this page!</a></Link>
Next, replace the content of pages/posts/first-post.js
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 it works. You now should have a link on each page, allowing you to go back and forth: