React / 18
Rendering lists with map
Turn an array of data into an array of elements with .map(). Filter or sort a copy first, handle the empty case, and give every item a key.
JSX can render arrays
Put an array of elements inside { } and React renders each one, in order:
<ul>{[<li key="a">Dosa</li>, <li key="b">Idli</li>]}</ul>So the job is to turn an array of data into an array of elements. That's exactly what .map() does.
1 · data
[{ id: "r1", name: "Tasty Bites" }, { id: "r2", name: "Green Bowl" }]2 · an array of elements
[<Card key="r1" … />, <Card key="r2" … />]3 · the screen
map: one element per item
const restaurants = [
{ id: "r1", name: "Tasty Bites", rating: 4.5 },
{ id: "r2", name: "Green Bowl", rating: 4.1 },
{ id: "r3", name: "Dosa Corner", rating: 3.8 },
];
export default function RestaurantList() {
return (
<div className="list">
{restaurants.map((r) => (
<RestaurantCard key={r.id} name={r.name} rating={r.rating} />
))}
</div>
);
}Read it as "for each restaurant r, make a RestaurantCard". Add a restaurant to the array and a card appears. No JSX changes.
The key tells React which card is which. It gets its own topic next; for now, always use the item's id.
Don't
Repeat yourself
<div className="list">
<RestaurantCard name="Tasty Bites" rating={4.5} />
<RestaurantCard name="Green Bowl" rating={4.1} />
<RestaurantCard name="Dosa Corner" rating={3.8} />
</div>Three copies to keep in sync, and it can't grow when the data does.
Do
Render from data
{restaurants.map((r) => (
<RestaurantCard key={r.id} name={r.name} rating={r.rating} />
))}Filter or sort first, then map
Chain array methods before .map():
const topRated = restaurants.filter((r) => r.rating >= 4.2);
const byRating = restaurants.toSorted((a, b) => b.rating - a.rating);filter and toSorted both return new arrays and leave restaurants alone. Avoid plain .sort() here: it reorders the original array in place. If you need it, sort a copy: [...restaurants].sort(…).
The empty case
A list can be empty, and a blank screen confuses people. Say so:
{topRated.length > 0 ? (
<ul>{topRated.map((r) => <li key={r.id}>{r.name}</li>)}</ul>
) : (
<p>No restaurants match.</p>
)}Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
