skip to Main Content

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


  1. 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:

    Array.from(map.values(), val => <div>{val}</div>);
    

    Here I’m using map.values() instead of map.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 the map directly to Array.from()) if you want to specify a key prop, which is best to do in React:

    Array.from(map, ([key, val]) => <div key={key}>{val}</div>);
    
    Login or Signup to reply.
  2. 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:

    const map = new Map([  ['2023-08-23', ['string1', 'string2']], ['2023-08-24', ['string3', 'string4']]]);
    const mapElements = Array.from(map.entries()).map(([date, strings]) => (<div key={date}>
    {strings.map((str, index) => (
      <span key={index}>{str}</span>
    ))}</div>));// Render the mapElements in your JSX
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search