umma.dev

Dynamic Routes with Next.js

How to set up dynamic routes in a Next.js application.

Getting Started

npm creat-next-app [app-name]
cd [app-name]
npm i
npm run dev

Setting Up Dynamic Routes

index.tsx:

const Home: NextPage = () => {
  import type { NextPage } from "next";
  import Link from "next/link";

  const dummyData: { id: number; name: string }[] = [
    {
      id: 1,
      name: "one",
    },
    {
      id: 2,
      name: "two",
    },
  ];

  return (
    <main>
      {dummyData.map((a: { id: number; name: string }) => (
        <Link key={a.id} href={`/${a.id}`}>
          <button>{a.name}</button>
        </Link>
      ))}
    </main>
  );
};

Create another file withinin pages and call it [id].tsx.

Add the following to the component. In this component, you will be able to see the id of each route passed from the index component.

import type { NextPage } from "next";
import { userouter } from "next/router";

const Details: NextPage = () => {
  const router = userRouter();
  const id = router.query.id;
  return <div>Details for {id}</div>;
};