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:
Let's create the
App component first:
First, let's focus on its
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
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:
createMonthElement method gets
month as a parameter and returns an instance of
Month component with
month is an object with month
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
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!