You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: beta/src/pages/learn/index.md
+54Lines changed: 54 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -216,6 +216,60 @@ If you don't have the `else` branch, you can also use a shorter [logical `&&` sy
216
216
217
217
If you're unfamiliar with this JavaScript syntax, you can start by always using `if...else`.
218
218
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
+
constproducts= [
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
+
constlistItems=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
+
constproducts= [
253
+
{ title:'Cabbage', id:1 },
254
+
{ title:'Garlic', id:2 },
255
+
{ title:'Apple', id:3 },
256
+
];
257
+
258
+
exportdefaultfunctionShoppingList() {
259
+
constlistItems=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
+
219
273
## Responding to events {/*responding-to-events*/}
220
274
221
275
You can respond to events by declaring event handler functions inside your components:
0 commit comments