I’ve got an issue where I am trying to loop over a map and return a <p>
element in each case. It isn’t working as I believe it should, however it is working for an array.
The code is as follows:
<div className="previousRounds">
{myTestMap.forEach(() => (
<p>I've looped over a map to print this</p> //This doesn't work
))}
{currentUsersPicks.map(() => (
<p>I've looped over an array to print this</p> //This works
))}
</div>
The map definitely exists and if I replace the <p></p>
tags with console.log
then I do get output printed to the console.
Here’s a screenshot of the webpage.
So why does this work for an array and not a map?
Expecting this to work whether it’s a map or array
2
Answers
forEach
returnsundefined
which produces no JSX. Yourmap
actually returns some JSX so that’s why it renders.If you change your callback in map to not use a return it will not render anything either:
The
map()
method returns a new array, whereas theforEach()
method does not return a new array. The map() method is used to transform the elements of an array, whereas the forEach() method is used to loop through the elements of an array.For Each
The following two code examples produce exactly the same result, you can think of forEach like the first more traditional for loop.
Map
The following two code examples also produce exactly the same result, you can think of map like the first more traditional approach on mapping.
So when you want to render items in react you need to use the map method on the array to return a new array containing your JSX. Here is an example:
You should always provide a key to your repeated JSX item, you can learn more about keys and why react uses them here.