Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Using Dynamic Routes to Load Data | Section
Building Web Apps with Next.js

bookUsing Dynamic Routes to Load Data

Свайпніть щоб показати меню

In many applications, pages depend on dynamic values from the URL. For example:

  • A product page → /products/123;
  • A blog post → /blog/post-1.

These values are used to load specific data for each page.

In Next.js, you can combine dynamic routes with data fetching to load the correct data based on the URL.

Example - Dynamic Route Structure

app/
  products/
    [id]/
      page.tsx

This route matches URLs like:

  • /products/1;
  • /products/42.

Accessing the Parameter

Inside the page, you can access the dynamic value using params.

export default async function ProductPage({ params }) {
  const id = params.id;

  return <h1>Product ID: {id}</h1>;
}

Loading Data Based on the Parameter

You can use this value to fetch data from an API:

export default async function ProductPage({ params }) {
  const res = await fetch(`https://api.example.com/products/${params.id}`);
  const product = await res.json();

  return <h1>{product.name}</h1>;
}

Now each URL loads different data.

How It Works

When a user visits /products/5, Next.js:

  1. Extracts the value 5 from the URL;
  2. Passes it as params.id;
  3. Fetches the corresponding data;
  4. Renders the page with that data.

Why This Pattern Is Important

Dynamic routes allow you to build data-driven pages without creating separate files for each item.

question mark

How do you access a dynamic route parameter in a Next.js page?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 24

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 1. Розділ 24
some-alt