Dynamic Routes in NextJS

In NextJS, you can create dynamic routes. Such routes assume that part of the URL can have an arbitrary value. For example, let's take the address /users/1, in which instead of one there can be any number, technically corresponding to the user id, which we want to display.

In this case, we don't need to create multiple folders for each possible number. It is enough to declare this part of the address dynamic. In this case, all requests of this kind will be handled by a common file page.jsx.

In order to make a dynamic parameter, you need to take the name of the corresponding folder in square brackets. In our case, it will be the following folder structure:

Let's create the corresponding component:

app/users/[id]/page.jsxexport default function User() {
  return <p>
    user
  </p>;
}

The parameter we set will be stored in a special object params. Let's output the value of this parameter:

app/users/[id]/page.jsxexport default function User({ params }) {
  return <p>
    user {params.id}
  </p>;
}
Задание 1

Create a route that handles addresses like /city/:name, where instead of :name there can be any string.

Задание 2

Create a route that handles addresses like /show/:country/:city, where instead of :country and :city there can be any strings.

Задание 3

Create a route that handles addresses like /post/:id, where instead of :id there can be any number.

Let the following array be given:

page.jsxlet posts = [
  'post1',
  'post2',
  'post3',
  'post4',
  'post5',
];

export default function Post() {
  
}

Make sure that depending on the value of the parameter id in the layout of the component, the corresponding post is displayed.

Задание 4

Create a route that handles addresses like /prod/:id, where instead of :id there can be any number.

Let the following array be given:

page.jsxlet prods = [
  {
    id: 1,
    name: 'prod1',
    cost: 100,
  },
  {
    id: 2,
    name: 'prod2',
    cost: 200,
  },
  {
    id: 3,
    name: 'prod3',
    cost: 300,
  },
];

export default function Prod() {
  
}

Make sure that depending on the value of the parameter id in the layout of the component, the corresponding product is displayed.