How to loop through arrays in React

Sunil Sandhu
Oct 27, 2018 · 6 min read
Image for post
Image for post

When building any type of web application, it’s very common that you will need to handle an array of data. In this article, let me show you how to loop through an array of data using React best practices, using real-world examples that you can take away and use in your own web applications.

Have you used the map function before?

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

So the map function was introduced to JavaScript in ES2015. It greatly simplifies the looping process and cuts out the need to use a simply for loop or a forEach function. Now there are some differences between for loop, forEach and map, but we won’t go into them here. The React docs strongly encourage the use of the map function, not just for its simplicity, but because it creates a new array from the data, rather than trying to mutate/overwrite existing data.

This second point is vital. If you are unsure about how to use map functions, I recommend that you take a moment to read this article about using map, filter and reduce.

Enjoying this article? If so, get more similar content by subscribing to Decoded, my YouTube channel!

Looping through an array of items in a shopping cart

Let us imagine that we are building an eCommerce website where we sell clothes. Our application will likely have a shopping cart that items get added to. So to begin with, our shopping cart will look something like this.

let shoppingCart = [];

But after a few items have been added, it may look something like this:

Now on our shopping cart page, we will want to output these items so that the user can see what they have ordered. Let’s see two very similar ways that we can handle this.

Inside of our App class constructor, we will create this.items and assign it to this.state.cart (remember, this is where we store items that get added to the cart). We then use the ES2015 map function to loop through each item in this.state.cart.

We pass our map function two parameters. The first is item which simply corresponds to a single item inside of our this.state.cart array. The second is a key, which React uses to help its renderer keep a track of each individual item. As you may have noticed, we didn’t set a key inside of our this.state.cart, we simply pass the item’s id as the key, by referencing inside of our map function. Anyway, we then output an <li> tag with {} inside of it.

Let’s just take a quick look at how this chunk of code in full:

Then later on in our code, when we want to use it, we simply create an outer <ul> tag, and put this.items inside of it, like so:

And just like that, our page will render each item in our shopping cart as a unique <li> item.

The second way that we could have handled this is very similar, and may feel a little more familiar.

Instead of putting our this.item block of code inside of the class constructor, we could have simply put it at the top of our render() function, like so:

This allows us to use the more traditional const syntax (or var or let if you prefer).

If we do this, it also means that we can write this instead:

Now some people will argue that you shouldn’t pollute the render() function, but when writing something fairly simple and not incredibly complex (I’m talking about thousands and thousands of lines of code here), it really doesn’t matter. So I would recommend that you go with whichever way feels more comfortable to you. As you progress with React, you will come to find a style that suits your project best.

Okay, so we know how to render lists using loops. But what if we want to loop through data to output lots of child components? How can we do this?

Well, it’s actually quite simple and very similar to what we have already been doing.

So let us just imagine that our shop has the following items:

And just to give you a clearer picture, this shop exists inside of this.state, inside of a constructor. It all looks like this:

So we have our shop items and now we want to create a child component which we call Item.js. The entire component file looks like this:

If you are unsure, we call this.props.item because we pass this.state.item into the child component when we call for it inside of the parent component. This may sound a bit strange, but bear with us and it will all make sense in a moment!

So going back to looping, this is what we would write to loop through the items in our shop:

As you can see, it’s pretty much the same concept that we used earlier. The only difference here is that instead of outputting <li> tags, we are now outputting <Item /> tags instead — which is the Item.js component we mentioned a moment ago! It’s as simple as that!

So when we call this.props.item inside of the Item.js component, it is a reference to <Item key={} item={item}/> , more specifically, item={item}. So if we called this product={item}, we would, instead, refer to this.props.product. Make sense?

You may have noticed that we had to wrap the entire functionality inside of curly braces {}. This is required so that React is able to understand that you are trying to express a function and not just render out plain text.

Another thing to also note here is that the three different ways we have looped through data can all be interchanged. So if you wanted to loop through an array of child components, but preferred the first method we showed you, then you can! At the end of the day, it’s all regular JavaScript!

So there you have it, we have shown you three powerful ways to loop through arrays using the latest JavaScript techniques in React. Now go use this newfound knowledge to make some amazing web applications!

Image for post
Image for post
Subscribe to Decoded, our official YouTube channel!

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store