How to Render an Array of DOM Elements using JSX in React
Suppose we want to render out a list of dogs (as one does) dynamically in a React component using JSX.
Solution 1: Create an array of DOM elements
One option is to render each JSX element and place them in an array.
const DogList = () => {
const dogBreeds = ['corgi', 'shih tzu', 'pug'];
const dogs = [];
for(const [index, value] of dogBreeds.entries()) {
dogs.push(<li key={index}>{value}</li>)
}
return <ul>{dogs}</ul>;
}
Solution 2: Use map()
to render an array
Another option is to use map()
in our JSX to avoid the for-of
loop.
const DogList = () => {
const dogBreeds = ['corgi', 'shih tzu', 'pug'];
return (
<ul>
{dogBreeds.map((value, index) => {
return <li key={index}>{value}</li>
})}
</ul>
)
}