NextJS, map, show data based on an identifier #201096
Replies: 3 comments 5 replies
-
|
Yes, this is standard practice.The key property is strictly for Next.js/React's internal rendering optimization, whereas your custom identifier handles the business logic.To achieve this, assign a unique value (like an ID) to the key property, and pass your specific layout identifier as a separate custom property. You can then use conditional logic (switch/if) or a component lookup map inside your loop to dynamically render different data and UI sections based on that identifier. |
Beta Was this translation helpful? Give feedback.
-
|
For filtering data based on an identifier in NextJS, here are a few approaches: 1. Using Array.filter(): const filteredData = data.filter(item => item.id === identifier)2. Using Array.find() for single item: const item = data.find(item => item.id === identifier)3. Using useMemo for performance: const filteredData = useMemo(() => {
return data.filter(item => item.id === identifier)
}, [data, identifier])4. If using API routes: // pages/api/items/[id].js
const { id } = req.query
const item = await fetchItem(id)Could you share more details about your data structure? That would help give a more specific solution. |
Beta Was this translation helpful? Give feedback.
-
|
For the bus trip case specifically — since you've got a route ID plus a direction flag (O/R), I'd group by both rather than trying to do it all in one .map(). Then render two sections, each mapping its own array, with key={trip.id} on the list item (key is just for React's diffing) and direction used purely for your UI logic (which section it lands in, which label/icon to show, etc.). If a route can have several trips per direction (different times), group again by route ID inside each list: That gives you { routeId: [trip, trip, ...] } per direction, which maps cleanly onto "one card per route, showing all available times." Keeps the filtering logic out of your JSX entirely — you do the grouping once (probably in a useMemo if trips is large or comes from an API), and the render just walks the already-grouped data. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
🏷️ Discussion Type
Question
Body
Is it possible to render separate sections on a page based on an identifier not a key? I know that the key must be unique and that's ok, but I need to show different details in each section.
Guidelines
Beta Was this translation helpful? Give feedback.
All reactions