Search code examples
javascriptreactjsreact-props

Mapping on a sending props ReactJs


This is the data

const people = [
    {
      img: 11,
      name: "Ahmed",
      job: "developer",
    },
    {
      img: 13,
      name: "Kazim",
      job: "Engineer",
    },
]

I'm trying to map these properties that I'm sending separately.

<Person person={people[0]} />
<Person person={people[1]}/>
<Person person={people[2]} />

I tried this

{people.map((i) => (
  <Person person={people[i]} />
))}

But it gives this error

TypeError: Cannot destructure property 'img' of 'props.person' as it is undefined.

I tried sending it along with the key as well, but it still gives the same error.

I tried this as well

 people.map((person,i) => {
      return (
        <Person
          key={i}
          img={person[i].img}
          name={person[i].name}
          job={person[i].job} 
        />
     );
  );

But it gives this error

TypeError: Cannot read property 'img' of undefined

Solution

  • The first argument to the callback for map is the element itself, not the index.

    {people.map((i) => (
      <Person person={i} />
    ))}