Skip to content
Advertisement

Reactjs map works but forEach doesn’t

I’m struggling to understand the difference between forEach and map. In the following render function if the ‘forEach’ is replaced with ‘map’ it works. I don’t understand why it doesn’t work with the ‘forEach’. Both {item.id} and {item.text} are present with both methods. So, why are the props for ‘TodoItem’ not being set when using ‘forEach’ ?

render() {    
  return(

     <ul>
        {this.props.items.forEach(function(item) {

           return (
              <TodoItem id={item.id} text={item.text} />)
        })} 
     </ul>
  );
}

So if ‘forEach’ doesn’t return anything how come this doesn’t work either:

render() {    
  return(

     <ul>
        {this.props.items.forEach(function(item) {               

              <TodoItem id={item.id} text={item.text} />
        })} 
     </ul>
  );
}

Advertisement

Answer

The map function returns an array of items and forEach just loop over them. To make this code work use :

render() {    
  const items = [];
  this.props.items
    .forEach(item => items.push(
                       <li>
                          <TodoItem id={item.id} key={item.id} text={item.text} />
                       </li>
                     ))

  return(
     <ul>{items}</ul>
  );
}
Advertisement