0

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!

5
  • Maps don't have a .map method. You also need to enclose JS expressions in {} delimiters when inside JSX in order to interpolate Commented Apr 21, 2021 at 2:23
  • Oops left our the curly brackets, updated question. For this case, how can the Map object be converted to a type that have the .map method? Otherwise, is there another method that Map has that we can use for this? Commented Apr 21, 2021 at 2:29
  • Pick one of the Map iteration methods suitable for your needs. (.map isn't one of them) Commented Apr 21, 2021 at 2:31
  • Thanks, using Array.from(myMap.entries()) allowed me to use the .map() method again. Is this a suggested way to do it? Commented Apr 21, 2021 at 2:35
  • 1
    Yes. For addtional context, Array.from(myMap) is equivalent to Array.from(myMap.entries()), which is also equivalent to [...myMap]. Commented Apr 21, 2021 at 2:50

1 Answer 1

2

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>
  )
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.