.map is not a function

Total
0
Shares

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

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like

How to use React?

This article will help you to know how to use React JS in web applications. React js creates static websites with optimized performance and speed. Step 1: Install create-react-app npm…
View Post