Languages
[Edit]
EN

Next.js - create dynamic routes

0 points
Created by:
Kenya-Spears
860

In this article, we would like to show you how to create dynamic routes in Next.js.

Practical example

In this example, we present how to display the details of the product with given id, when the user navigates to the /product route followed by the id of the product.

Example URL:

http://localhost:3000/product/1

Result:

The route will return the details about the product with id = 1.

Project structure

In order to create dynamic routes, need to create the following project structure:

  1. inside pages/ directory, create the separate product/ folder for the products,
  2. inside product/ folder, create [id].js file - by wraping the id with square brackets we create a dynamic route, where we can pass id of the individual products.
  3. product/index.js file, will be mapped to the main /product route,
/next.js-project/
    ├─ next/
    ├─ node_modules/
    └─ pages/
	    ├─ api/
	    └─ product/
            ├─ index.js
            └─ [id].js

Example components

product/index.js:

function Product() {
    return <h1>Product main page</h1>;
}

export default Product;

product/[id].js:

import { useRouter } from 'next/router';

function ProductDetails() {
    const router = useRouter();
    const id = router.query.id; // gets id query parameter
    return <h1>Product {id} details</h1>;
}

export default ProductDetails;

Web browser preview

Next.js - dynamic routing preview
Next.js - dynamic routing preview

Alternative titles

  1. Next.js - dynamic routing
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join