map() can only be used with Arrays. So, if you are getting error .map is not a function, you are probably using it on either the objects or other variables which are not array.

Consider this example –

var superHero = {
  'hero' : [
              'Captain America',
              'Ironman',
              'Hulk',
              'Thor',
              'Scarlet Witch',
           ],
}

const superHeroList = () => {
  return (
     <>
       {
         superHero.map(hero => {
           return (<p>{hero}</p>)
         })
       }
     </>
  )
}

The above code will create error in map function. Because superHero is not an array. Else it’s an object which has a property, hero, which is an array of super heroes.

To correctly call map function, we need to change our code and instead of calling it as superHero.map, we need to call it as superHero.hero.map.

var superHero = {
  'hero' : [
              'Captain America',
              'Ironman',
              'Hulk',
              'Thor',
              'Scarlet Witch',
           ],
}

const superHeroList = () => {
  return (
     <>
       {
         superHero.hero.map(hero => {
           return (<p>{hero}</p>)
         })
       }
     </>
  )
}

    Tweet this to help others

Live Demo

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles