Reactjs map works but forEach doesn't
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>
);
}
Try this simple example for understand why forEach doesn't work in this context:
[1,2,3].forEach((n)=> n); => returns undefined
[1,2,3].map((n)=> n); => returns [1,2,3]
As @Nenad Vracar mentioned map
will actually return stuff. If you wanted to do somethings to another array, object or piece of code you could use forEach
. But since you want to return something that ends up being shown on the DOM. Use map
.
Also, don't forget to return
whatever you're mapping. It's a common mistake because you don't need to use the return for forEach
.