Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use a Map object in JSX?

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;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading