PL
React - pętla wewnątrz JSX
0
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:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const Row = () => {
return (
<p>Row</p>
);
}
const App = () => {
const size = 5;
return (
<div>
{Array(size).fill().map((x, i) =>
<Row key={i} />
)}
</div>
);
}
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);