Sylvester Agubata
Sylvester Agubata

Reputation: 7

i keep getting this error "Cannot read property 'map' of undefined"


    TypeError: Cannot read property 'map' of undefined
      ClassCard
      C:/Users/hp/Desktop/abe2021/src/components/ClassList/ClassCard.js:8
         5 | 
         6 | const ClassCard = ({Names}) => {
         7 | 
      >  8 |    const cardComp = Names.map((Names, i) => {
           | ^   9 |        return <ClassList 
        10 |        key={i} 
        11 |        id={Names[i].id} 

i am trying to map through an arrary in my react project and i keep getting the error above

Upvotes: 0

Views: 30

Answers (2)

Salah Eddine Makdour
Salah Eddine Makdour

Reputation: 1042

Well, that's ez to fix, maybe in another components you have edited Names in a way that doesn't make it an array anymore, that's why you can't use the method .map with it, try to check if the type of Names is array or not. Maybe you should also provide us with more code so we can see where exactly the mistake is.

Thanks :)

Upvotes: 0

Joe Lloyd
Joe Lloyd

Reputation: 22353

Names is undefined (or just not an array)

You cannot map over undefined or null since map is an array method.

Assign a default empty array value

const ClassCard = ({Names = []}) => {
  const cardComp = Names.map((Names, i) => {
  ...
  }
}

or check if your Names array exists

const ClassCard = ({Names}) => {
  const cardComp = Names && Names.map((Names, i) => {
  ...
  }
}

Upvotes: 1

Related Questions