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>
);
}
forEach() is not designed to return a value. Its primary purpose is to transform every array element, but nothing else. The method doesn't return a new array; it returns undefined . Instead, React developers use an alternative method, .
Using the forEach() method in React # The forEach() method can be used to iterate over an array outside of your JSX code in React. If you need to iterate over an array and render its elements directly in your JSX code, use the map() method instead.
You are correct, forEach doesn't return anything, use map instead, it will return an array of JSX components.
Differences between forEach() and map() methods:The forEach() method does not create a new array based on the given array. The map() method creates an entirely new array. The forEach() method returns “undefined“. The map() method returns the newly created array according to the provided callback function.
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
.
Basically map
returns an array while forEach
returns nothing,
in jsx/react context you need to return a list of components/node-tags that the parser will transform in nodes both in the real and virtual dom;
working by side-effect like forEach does you won't have anything to parse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With