Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript React Basics (2018) Introducing Props Iterating and Rendering with map()

karan Badhwar
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
karan Badhwar
Web Development Techdegree Graduate 18,135 Points

Why forEach() is not working

why forEach() is not working and we are not even returning any any array we just make make calls to the <Player /> component ? why only map() is working?

2 Answers

Laura Coronel
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Laura Coronel
Treehouse Teacher

From my understanding the map() method returns an array of <Player /> components like so :

[
<Player name="Guil" score={50} />,
<Player name="Treasure" score={90} />,
<Player name="Ashley" score={85} />,
<Player name="James" score={80} />
]

Babel comes in and transforms this to React.create Element like so:

[
React.createElement(Player, {
  name: "Guil",
  score: 50
}), 
React.createElement(Player, {
  name: "Treasure",
  score: 90
}), 
React.createElement(Player, {
  name: "Ashley",
  score: 85
}), 
React.createElement(Player, {
  name: "James",
  score: 80
})
];

The behind the scenes React takes this array and transforms it to a list of elements. In our example the React.createElement() first parameter is Player which is a functional component that will return the Player component's elements.

I hope this helps!

If you want to learn more here's React's doc on createElement(). And you can even enter your JSX into Babels compiler

Laura Coronel
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Laura Coronel
Treehouse Teacher

Great question karan karan. Behind the scenes React takes the array (created by map() method) and transforms them into a list of elements, in this example: <Players /> components. The forEach() method will not work because it returns undefined. React needs the array provided by map() to create elements which will then be rendered to the browser.

For more resources here's the link to List and Keys in the React docs.

karan Badhwar
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
karan Badhwar
Web Development Techdegree Graduate 18,135 Points

Laura Coronel, Thankyou for explaining. So basically you are saying when the Babel converts the JSX to React.createElement it stores the method in an anonymous array? but when we called the <Player /> component doesn't it just redirects to the Component and create an element?