0
    const robots = [
  {
    id: 1,
      name: 'Leanne Graham',
      username: 'Bret',

  },
  {
    id: 2,
    name: 'Ervin Howell',
    username: 'Antonette',

  },
  {
    id: 3,
    name: 'Clementine Bauch',
    username: 'Samantha',

  },
  {
    id: 4,
    name: 'Patricia Lebsack',
    username: 'Karianne',

  },
  {
    id: 5,
    name: 'Chelsey Dietrich',
    username: 'Kamren',

   },
   {
    id: 6,
    name: 'Mrs. Dennis Schulist',
    username: 'Leopoldo_Corkery',

  },
  {
    id: 7,
    name: 'Kurtis Weissnat',
    username: 'Elwyn.Skiles',

  },
  {
    id: 8,
     name: 'Nicholas Runolfsdottir V',
    username: 'Maxime_Nienow',

  },
  {
    id: 9,
    name: 'Glenna Reichert',
    username: 'Delphine',

  },
  {
    id: 10,
    name: 'Clementina DuBuque',
    username: 'Moriah.Stanton',

  }
];



let cardComp = robots.forEach((element,index)=> {
        return (<Card  id = {robots[index].id} Name = {robots[index].name}
        user ={robots[index].username} mail = {robots[index].email}/>)
      });

The following Code is not working in react.js But the same code when I replace the forEach loop with maps works fine. Why does it not work with the forEach loop? When I try to get the value from the array of objects using normal javascript, it works just fine and I am able to get all the values in the array. But it's not working in the react.js with a forEach loop.

Harsha pps
  • 2,012
  • 2
  • 25
  • 35
  • There are some answers here that might be helpful https://stackoverflow.com/questions/34426458/javascript-difference-between-foreach-and-map – Kunukn Jun 26 '18 at 12:05
  • `foreach` by nature doesn't return anything, so having a `return` statement in a `foreach` loop doesn't make sense. `map` returns an array of _stuff_, so a `return` statement in a `map` makes sense. As a guess, I imagine the compiler falls over as it doesn't understand why a `return` statement is in a `foreach` loop. – James Whiteley Jun 26 '18 at 12:28
  • Use Array.map instead of Array.forEach – desoares Jun 26 '18 at 12:30

1 Answers1

3
let cardComp = robots.forEach((element,index)=> {
        return (<Card  id = {robots[index].id} Name = {robots[index].name}
        user ={robots[index].username} mail = {robots[index].email}/>)
      });

forEach in javascript does not return anything

instead use map that returns new array

let cardComp = robots.map((element) => {
      return (<Card id={element.id} Name={element.name} user={element.username} mail={element.email}/>)
    });

See MDN prototype information about forEach

enter image description here

and the map

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
    // Return element for new_array
}[, thisArg])

enter image description here

Manoz
  • 6,507
  • 13
  • 68
  • 114