How do we generate React components by looping through an array of items inside JSX syntax?
Let's build a simple React application:
You can find the full source code in this GitHub repository.
Our application is going to render a list of months. It will be made of two components: App
and Month
.
Let's create the App
component first:
First, let's focus on its render
method:
We see three div
elements with class names that you might recognize if you're familiar with Bootstrap. Bootstrap helps us create layout for our page.
Inside of the div
elements we have a ul
element that has a JavaScript expression wrapped in {
and }
:
We can add JavaScript expressions inside of JSX syntax. JSX syntax itself is an expression too. In that JavaScript expression we're looping through an array called MONTHS
and for each item in that array we call this.createMonthElement
method and pass an array item as an argument to it.
As you have guessed, the this.createMonthElement
method returns another JSX expression that renders a month name. Let's take a look at it:
The createMonthElement
method gets month
as a parameter and returns an instance of Month
component with month
and key
props.
The month
is an object with month name
and number
for example:
It makes sense why we pass month
object to Month
component as a prop, but why do we need to pass the key
prop? When we create React elements dynamically we need to help React to uniquely identify those elements, so that React could figure out how to update the DOM efficiently.
Now let's take a look at the Month
component:
As you can see, the Month
component renders li
element with month name:
Now you know how to loop through array of elements inside of JSX in React.
Thank you for reading this React tutorial!
Please take a look at the complete source code on GitHub and the live version of our app.
I hope you've enjoyed this tutorial and I would love to hear your feedback in the comments. You can get in touch with me via Twitter and email.