Skip to content

Commit 2d6052e

Browse files
committed
tweak
1 parent 0fe37d5 commit 2d6052e

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

beta/src/pages/learn/index.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,60 @@ If you don't have the `else` branch, you can also use a shorter [logical `&&` sy
216216
217217
If you're unfamiliar with this JavaScript syntax, you can start by always using `if...else`.
218218
219+
## Rendering lists {/*rendering-lists*/}
220+
221+
You will rely on JavaScript features like [`for` loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) and the [array `map()` function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to render lists of components.
222+
223+
For example, let's say you have an array of products:
224+
225+
```js
226+
const products = [
227+
{ title: 'Cabbage', id: 1 },
228+
{ title: 'Garlic', id: 2 },
229+
{ title: 'Apple', id: 3 },
230+
];
231+
```
232+
233+
Inside your component, use the `map()` function to transform an array of products into an array of `<li>` items:
234+
235+
```js
236+
const listItems = products.map(product =>
237+
<li key={product.id}>
238+
{product.title}
239+
</li>
240+
);
241+
242+
return (
243+
<ul>{listItems}</ul>
244+
);
245+
```
246+
247+
Notice how `<li>` has a `key` attribute. A key helps React figure out what happened when list items are inserted, removed, or reordered. Usually you should use a key from your data, such as a database ID. Keys should be unique among items in the same parent tag. Although you can technically specify index as a key, your list won't work correctly when items are inserted, removed, or reordered. Always try to use ID as a key if you can.
248+
249+
<Sandpack>
250+
251+
```js
252+
const products = [
253+
{ title: 'Cabbage', id: 1 },
254+
{ title: 'Garlic', id: 2 },
255+
{ title: 'Apple', id: 3 },
256+
];
257+
258+
export default function ShoppingList() {
259+
const listItems = products.map(product =>
260+
<li key={product.id}>
261+
{product.title}
262+
</li>
263+
);
264+
265+
return (
266+
<ul>{listItems}</ul>
267+
);
268+
}
269+
```
270+
271+
</Sandpack>
272+
219273
## Responding to events {/*responding-to-events*/}
220274
221275
You can respond to events by declaring event handler functions inside your components:

0 commit comments

Comments
 (0)