[React] How to Loop Through Arrays in JSX

Arrays are quite common when using React, typically as a variable stored in your state.

Whether it’s an array of integers, strings, or even objects, you’ll likely need to iterate through it at some point in your JSX in order to display each value.

The way you do this is by using the JavaScript function `map`.

I’ll go through a few examples to break down how to do this. It will quickly become second nature once you’re used to it.

Looping Through Lists Using Map in JSX

The most common reason that you need to loop through an array is to build an HTML list where you list out each value in an array.

Here’s a simple example of a component where there’s an array of numbers that we want to put in a list

As expected, that gives you an output of:

There’s a few things to note here.

First, if you don’t put a “key” attribute in your list items, you will see a warning in the browser console:

“Warning: Each child in a list should have a unique "key" prop.”

It will still likely work, but can affect performance. The key attribute is supposed to be a unique identifier that React can use internally to detect changes efficiently.

While you can generate a random number or string as a key, for most simple lists, using the list index is fine, and convenient since you can pass it through `map` as an input.

Breaking Down JSX Loops in More Detail

If you just needed a refresher, you’re probably good with just the above example.

But if you’re new to React, I’ll break down how this works in more detail to make it clearer.

`Map` can be called on any iterable, an array in this case.

It accepts a single input - a function. Each individual element of the iterable is passed to it one at a time, you can name that input variable whatever you’d like.

Above, map is called on “myArray”.

Then, map is passed a function that takes each element of “myArray” as an input, one at a time.

That function then returns that value in a `div`. Note that `index` can always be added as a secondary input, and that keys are only needed for elements like list items (not divs).

So, that map function will return and display each of those divs in order.

Using Map Without ES6 Arrow Functions

`Map` does not require you to use arrow functions, it’s just more convenient. But it can be confusing if you’re new to them.

Below is the same inner loop from the original example again, but written with standard function syntax, it renders the exact same list.

Not as tidy, but works just as well, so do whichever you’re more comfortable with.