Loops in JSX
More often than not we'll be dealing with lists and collections and not just simple singular items. That means we'll need to iterate over data, but there's no way to use for loops in JSX. Let's use .map.
1
const App: React.FC = () => {
2
const products: Product[] = [
3
{
4
name: "JavaScript: The Definitive Guide",
5
description: `Since 1996, JavaScript: The Definitive Guide...`,
6
price: 28.89
7
},
8
{
9
name: "Eloquent JavaScript",
10
description: `JavaScript lies at the heart...`,
11
price: 21.22
12
},
13
{
14
name: "JavaScript: The Good Parts",
15
description: `Most programming languages...`,
16
price: 16.59
17
}
18
]
19
20
return (
21
<section>
22
<h1>Products</h1>
23
{ products.map(product => (
24
<div key={product.name}>
25
<header>{ product.name }</header>
26
<p>
27
{ product.description }
28
</p>
29
<span>{ product.price }$</span>
30
</div>
31
)) }
32
</section>
33
)
34
}
Copied!
Overall, quite straightforward: there's an array of items, over which we iterate using .map and return some JSX for each element. Similar to using components, each piece of JSX returned by the .map transformation must have exactly one root element.
There's also the key property on the root element of each product. This not strictly required (will work, React will just complain), but it allows React to easily distinguish between elements during the reconcilation process. Should be unique for each element in the array.

Resources

Copy link
Contents
Resources