Generating Tags from an Array of Data in React
Let's say we have some array with some data, for example, like this:
function App() {
const arr = [1, 2, 3, 4, 5];
}
Let's put each element of this array into a paragraph and output these paragraphs in a div. For this, we can use any convenient JavaScript loop. For example, the usual for-of
:
function App() {
const arr = [1, 2, 3, 4, 5];
const res = [];
for (const elem of arr) {
res.push(<p>{elem}</p>);
}
return <div>
{res}
</div>;
}
However, in React, it is more common to use the map
method for such things:
function App() {
const arr = [1, 2, 3, 4, 5];
const res = arr.map(function(item) {
return <p>{item}</p>;
});
return <div>
{res}
</div>;
}
Given an array:
function App() {
const arr = ['a', 'b', 'c', 'd', 'e'];
}
Using this array, generate the following code:
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
<li>e</li>
</ul>