How to link two or more pages in Next.js
This tutorial builds upon the first Next.js tutorial, which covers how to install Next.js. In the previous tutorial, we created a website with a single page.
Now, we want to add a second page to our website, a blog posts list. This page will be served at /blog
and initially, it will be a simple static page similar to our index.js
component.
After saving the new file, the npm run dev
process, which is already running, will render the new page without the need to restart it.
When we visit the URL http://localhost:3000/blog, we can see the new page.
The terminal will display the following message:
The URL /blog
is determined by the filename and its position under the pages
folder. For example, creating a pages/hey/ho
page will be available at http://localhost:3000/hey/ho.
The component name inside the file does not affect the URL.
If we inspect the source of the page, we can see that the bundle loaded for the blog page is /_next/static/development/pages/blog.js
, not /_next/static/development/pages/index.js
like the home page. This is because Next.js automatically splits the code so that the bundle for the home page is not needed when serving the blog page.
In blog.js
, we can export an anonymous function:
export default () => (
<div>
<h1>Blog</h1>
</div>
)
Or, if you prefer the non-arrow function syntax:
export default function() {
return (
<div>
<h1>Blog</h1>
</div>
)
}
Now that we have two pages defined by index.js
and blog.js
, we can introduce links.
In regular HTML, we use the a
tag to create links between pages:
<a href="/blog">Blog</a>
However, in Next.js, we cannot use plain a
tags for links. Next.js provides a component called Link
that solves this issue.
We import the Link
component:
import Link from 'next/link'
Then, we can use it to wrap our link:
import Link from 'next/link'
const Index = () => (
<div>
<h1>Home page</h1>
<Link href='/blog'>
<a>Blog</a>
</Link>
</div>
)
export default Index
Now, if we click on the link, we will see that only the blog.js
bundle is loaded when we move to the blog page.
The page loads much faster, and the URL changes seamlessly using the browser History API.
This is client-side rendering in action.
If we press the back button, the browser will not load anything because it still has the old index.js
bundle in place, ready to load the /index
route. This behavior is automatic.
This is just one way to handle linking in Next.js, but it is the simplest method.