⊗jsnxPmRtDy 19 of 57 menu

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:

  • /app/
    • /users/
      • /[id]/

Let's create the corresponding component:

export 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:

export default function User({ params }) { return <p> user {params.id} </p>; }

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

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

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

Let the following array be given:

let 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.

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

Let the following array be given:

let 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.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline