Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
51
rated 0 times [  56] [ 5]  / answers: 1 / hits: 29926  / 7 Years ago, wed, november 22, 2017, 12:00:00

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>
);
}

More From » reactjs

 Answers
0

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>
);
}

[#55862] Monday, November 20, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
khalilb

Total Points: 173
Total Questions: 110
Total Answers: 105

Location: Honduras
Member since Thu, Mar 23, 2023
1 Year ago
;