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 Solution: Render the Stars

I always saw people using map inside render function, in this case wans't possible to use map?

Implementation of map function.

3 Answers

If I am not mistaken map can only be used with arrays.

Ivan Kazakov
PLUS
Ivan Kazakov
Courses Plus Student 43,317 Points
{[...Array(5).keys()].map(i => <Star key={i}/>)}

inside the render() worked for me.

James Crosslin
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
James Crosslin
Full Stack JavaScript Techdegree Graduate 16,882 Points

I'll break this down since nobody has done it yet, and you can test each step of this in the console in your browser or text editor. You'll be able to see exactly what is happening.

Array(5) creates an empty array with 5 empty spaces. The problem is that these are just pointers and do not have values, so we have to get values somehow if we plan to use this empty array. Array(5).keys() creates an iterator with the values of each index in the array, which would be the numbers 0-4, [...Array(5).keys()] spreads the iterator into an array that is usable, i.e. [0, 1, 2, 3, 4]. [...Array(5).keys()].map(i => <Star key={i} />) takes each value of the previous array and uses that value as the key of your component in a map. Map creates a new array of returned values, and because there is an implicit return in this one line arrow function, the new array will be composed of Star components with a key equal to its own index.

I did mine similarly, but I used

Array(5).fill().map((_, i) => <Star key={i} />)

Array(5).fill() fills the array with the values undefined instead. It lets me skip the spreading into an array literal. My underscore in the map method is because I do not use the original value in the map and I want to make that clear to other developers (and myself) who come to look at this code later.

Thank you for answers. It's right, I didn't pay attention, map works just with array, so needs to convert to an array. Spread and keys because it's an object, good solution. I still have doubts about how work with objects.