Home > Software engineering >  Map function on an array not working in React
Map function on an array not working in React

Time:09-17

I'm new to ReactJS. Somehow, I'm unable to get proper output using map on array.

I have an array named pets.

  const pets = [{
    name: 'Bruno',
    type: 'Dog',
    description: 'Bruno is funny and lovable',
    skills: ['fetch', 'being cute', 'roll over'],
    image: 'https://www.dogbreedinfo.com/images17/LabmaranerCasey6Weeks1.JPG'
  },
  {
    name: 'Rocky',
    type: 'Dog',
    description: 'Rocky is funny and lovable',
    skills: ['bite', 'being cute', 'roll over'],
    image: 'https://st.depositphotos.com/1000291/3041/i/950/depositphotos_30415145-stock-photo-white-labrador-puppy.jpg'
  }];

And I'm trying to display using map as below.

  <div>
    <h1>My pets</h1>
    <ul>
      {
        pets.map((pet, index) => {             
          <li key={index}>
            <h1> {pet.name} </h1>
          </li>
        })
      }
    </ul>

  </div>

Doing this is not displaying any data from the array.

What is wrong with my code , can someone tell me?

CodePudding user response:

yes, you forgot to return, you can check Implicit vs Explicit return here

you are doing explicit return, so it's required to write return keyword yourself... as

{
    pets.map((pet, index) => {             
      return(<li key={index}>
        <h1> {pet.name} </h1>
      </li>)
    })
  }

or turn in to implicit as below:

{
    pets.map((pet, index) =>(             
        <li key={index}>
          <h1> {pet.name} </h1>
        </li>
      )
    )
}

CodePudding user response:

You just need to add a return keyword, happy learning :)

 <div>
              <h1>My pets</h1>
              <ul>
                {
                  pets.map((pet, index) => {  
                              
                    return <li key={index}>
                      <h1> {pet.name} </h1>
                    </li>
                  })
                }
              </ul>
          
            </div>

CodePudding user response:

Do it like this ...

<div><h1>My pets</h1>
<ul>
  {
    pets.map((pet, index) => (            
      <li key={index}>
        <h1> {pet.name} </h1>
      </li>
    ))
  }
</ul></div>

CodePudding user response:

You should use the return in li tag or remove the curly braces.

  • Related