Sometimes, we want to loop and render elements in React without an array of objects to map.
In this article, we’ll look at how to loop and render elements in React without an array of objects to map.
How to loop and render elements in React without an array of objects to map?
To loop and render elements in React without an array of objects to map, we create an array.
For instance, we write
const Comp = ({ level }) => {
//...
return Array.from({ length: level }, (item, index) => (
<span className="indent" key={index}></span>
));
};
to call Array.from
with { length: level }
to create an array with the length
set to level
.
Then we call it with a callback that maps the empty array entries to spans.
Conclusion
To loop and render elements in React without an array of objects to map, we create an array.