/

Linking two pages in Next.js using Link

Linking two pages in Next.js using Link

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.

Screenshot

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.

Screenshot

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.

Screenshot

The terminal will display the following message:

Screenshot

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.

Screenshot

In blog.js, we can export an anonymous function:

1
2
3
4
5
export default () => (
<div>
<h1>Blog</h1>
</div>
)

Or, if you prefer the non-arrow function syntax:

1
2
3
4
5
6
7
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:

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
2
3
4
5
6
7
8
9
10
11
12
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.

Screenshot

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”]