⊗jsnxPmNvDL 48 of 57 menu

Dynamic Link Generation in NextJS

Let's say we have a file with user data:

export default users = [ { id: 1, name: 'name1', surn: 'surn1', }, { id: 2, name: 'name2', surn: 'surn2', }, { id: 3, name: 'name3', surn: 'surn3', }, ];

Let's create two components. The first component will show a list of users with links to their detailed description. The second component will display this detailed description.

Let the URL /users/list display the list of all users, and the URL /users/show/:id - a specific user by their id.

To do this, we will create the following file structure:

  • /app/
    • /users/
      • users.js
      • /list/
        • page.jsx
      • /show/[id]/
        • page.jsx

Let's create the first component, in which we will dynamically generate links in a loop, substituting the id of each user into them:

import users from '../users.js'; import Link from 'next/link'; export default function List() { let list = users.map(user => { return <li> <Link href={`/users/show/${user.id}`}> {user.name} </Link> </li>; }); return <ul> {list} </ul>; }

Let's create a component to display a specific user by their id:

import users from '../../users.js'; export default function User({params}) { let user = users[params.id]; return <div> <span>{user.id}</span> <span>{user.name}</span> <span>{user.surn}</span> </div>; }

Given the following array:

let prods = [ { id: 1, name: 'prod1', cost: 100, desc: 'desc1', }, { id: 2, name: 'prod2', cost: 200, desc: 'desc2', }, { id: 3, name: 'prod3', cost: 300, desc: 'desc3', }, ];

Create two components. Let the first one show a list of products as links to the full product description. Let the second component show the detailed product description.

Make it so that if a non-existent product id is passed in the URL, a 404 error is displayed on the screen.

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