Dynamic Routes

Polishing the Index Page

As the final step, let’s update our index page (pages/index.js).

In particular, we need to add links to each post page. We’ll be using the Link component, but we need to do something differently this time.

To link to a page with dynamic routes, you need to use the Link component differently. In our case, to link to /posts/ssg-ssr, you need to write it like this:

<Link href="/posts/[id]" as="/posts/ssg-ssr">

As you can see, you need to use [id] for href and the actual path (ssg-ssr) for the as prop.

Let’s implement it. First, import Link and Date in pages/index.js:

import Link from 'next/link'
import Date from '../components/date'

Then, near the bottom of the Home component, replace the li tag with the following:

<li className={utilStyles.listItem} key={id}>
  <Link href="/posts/[id]" as={`/posts/${id}`}>
  <br />
  <small className={utilStyles.lightText}>
    <Date dateString={date} />

It should now have the links to each article:

If something is not working, make sure that your code looks like this.

That’s it! Before we wrap up this lesson, let’s talk about some tips for dynamic routes on the next page.