Linking two pages in Next.js using Link
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:
1 | export default () => ( |
Or, if you prefer the non-arrow function syntax:
1 | export default function() { |
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:
1 | <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:
1 | import Link from 'next/link' |
Then, we can use it to wrap our link:
1 | import Link from 'next/link' |
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.
tags: [“Next.js”, “Linking pages”, “Client-side rendering”, “Web development”]