⊗jsnxPmImCD 27 of 57 menu

Shared Component Data in NextJS

There are situations when several components need to access the same data. As an example, let's say we have a certain array of users. On one route, we want to show a list of users, and on another route with a dynamic parameter - the description of a specific user by their id.

Let's implement what was described. We will create the following file structure:

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

Let's create a separate 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 a component to display the list of users:

import users from '../users.js'; export default function List() { let list = users.map(user => { return <li> {user.name} </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, and the second one show detailed product description.

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