What is the best way of iterating over a Map
object in JSX?
const map = new Map<string, string[]>([
'2023-08-23': ['string1', 'string2'],
'2023-08-24': ['string3', 'string4']
]);
I can do it with a helper function, but I’m wondering if there’s a better way:
const mapMap = () => {
const iterator = map.entries();
const els = [];
for (let i = 0; i < map.size; i++) {
els.push(<div>{iterator.next().value.at(1)}</div>);
}
return els;
}
2
Answers
The
Array.from()
method is able to iterate the iterator for you, and will produce an array based on what the iterator produces, as well as what you return from the mapping function if you supply one, for example:Here I’m using
map.values()
instead ofmap.entries()
as in your code you’re only using the value, however, you may want to continue using.entries()
(which is implicitly used if you pass themap
directly toArray.from()
) if you want to specify akey
prop, which is best to do in React:Iterating over a Map object in JSX can be done more efficiently and with cleaner code using the map() function. Here’s how you can achieve this:
In this example, Array.from(map.entries()) is used to convert the Map entries into an array of [key, value] pairs. Then, the map() function is used to iterate over each entry and create a JSX element for each date and its corresponding strings.
Remember to provide a unique key prop for each iterated element, which is necessary for React’s rendering optimization.
By using the map() function, you can achieve the desired output more efficiently and with a more readable code structure.