React loops
How to use loops in React
Tutorial describing how to easily use loops in react components.Disclaimer: In this lesson, we will quickly go through loops in React. I assume that you already know how to code loops in JS - if you don't then check this tutorial first.
For loop
Currently, we have our main App Component
and the child component:
A typical JS for loop looks like this one below:
Let's try to use it within our App component:
As soon as we save the file, the compiler will raise an Unexpected token error:

Apparently, React does not like for loops in its render()
method! How do we solve this?
What we need to do is to use a loop in a separate function outside render()
,
but still inside the class. Then we can call the creating function inside render to get the result.
and call it within the render()
method:
Preview:

Looping through components
Let's create an array containing some events in our App component:
Since we cannot use a for loop directly in our render()
method,
let's modify our myLoopFunction()
to work with our components:
As you might notice we made a few changes:
- we used an array instead of a string variable to collect loop output
- instead of hard-coded values, we are looping until we reach the length of
our events array (
events.length
) - we refer to corresponding events in a table using an iterator (
i
) (this.state.events[i]
)
Preview:

It works, however, there is a much better and easy way to loop within the render()
method without using extra function.
Looping through components
Instead of typical loop we can use map()
function:
The result is the same and it's much shorter. Furthermore we can use
it directly inside the render()
method.
We can now delete our myLoopFunction()
since we don't need it anymore.
"key" attribute
The map()
function makes it easier to iterate through arrays, however,
there is one important thing to remember while using map()
in React.
When you open a console, you will see that React complains about missing key attribute:

It is important for React to maintain the key for each element generated by the map()
function.
This way React can handle the minimal DOM change. Let's add a few more items to our events array:
Now each element has its own id, which we will use as a key. We also extended some of our events with a location as well as a description.
Let's update our map correspondingly:
The last step is to update our Event component to render our new metadata:
Preview:

Some of the values are empty and looks odd, that's why we will learn more about conditional rendering in the next lesson.