Nyxynyx
Nyxynyx

Reputation: 63619

Unable to Iterate Typescript Map object using .map() in React Component

If we have a Typescript Map object, how do we iterate it in order to render a number of items in React?

Using .map on the Map object causes Typescript to complain:

export function Foo() {

    type MyMap = Map<string, number>;
    const myMap: MyMap = new Map<string, number>();

    return (
        <div>
        {
            myMap.map(x => {  
                return (
                    <Foo key={x.id} score={x.score} />
                )
            })
        }
        </div>
    )
}

Thanks!

Upvotes: 0

Views: 1210

Answers (1)

Arman Charan
Arman Charan

Reputation: 5797

In JavaScript/TypeScript, Array.prototype.map() is specific to arrays.

Consequently, an array must first be derived from myMap, in order for Array.prototype.map to be used on its contents.

This is often done using Array.from(), or more tersely using spread syntax.

See below for a practical example.

export function Foo() {
  const myMap: MyMap = new Map<string, number>();

  return (
      <div>
        {[...myMap].map(([id, score]) => <Foo key={id} score={score} />)}
      </div>
  )
}

Upvotes: 2

Related Questions