EN
React - loop inside JSX
5 points
In this article, we would like to show you how to create a loop in React JSX.
Below example shows how to render specified number of Row
components in our App
in three steps:
- With
Array(size)
we create an empty array with the specified size, - using
fill()
method we fill the array with undefined values, - with
map()
we loop over the array renderingRow
elements and assigning unique keys to them.
Practical example:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const Row = () => {
6
return (
7
<p>Row</p>
8
);
9
}
10
11
const App = () => {
12
const size = 5;
13
return (
14
<div>
15
{Array(size).fill().map((x, i) =>
16
<Row key={i} />
17
)}
18
</div>
19
);
20
}
21
22
const root = document.querySelector('#root');
23
ReactDOM.render(<App />, root);