DEV Community

loading...

Loop through Arrays with MAP() in React

vish448 profile image Vishang ・2 min read

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

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/overwriting existing data. With your react application there will be more likely chances where you have to gather the data from API in the form of JSON and grab data according to your requirements. Map() is the best way to iterate through those data and fetch what you need.

Let's take an example


let cart = [
{id: 1, itemName: 'cap',price:10 },
{id: 2, itemName: 'socks',price:20 },
{id: 3, itemName: 'hoodie',price:30 }
]

inside of our App class constructor, we will create this.cartItems and assign it to this.state.cart (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 two arguments with it.

  1. item: single item inside out this.state.cart
  2. key: React uses to help its renderer keep a track of each individual item.

this.cartItems = this.cart.map((item, key) => 
    
  • {item.itemName}
  • )

    and we want to use to show cartItems in our code we simply call it via

      {this.cartItems}

    Instead of calling it from constructor we can call it in our render method

    
    render() {
        const cartItems = this.state.cart.map((item,key) => 
            
  • {item.itemName}
  • )

    and we can just call it like

    
    
      {cartItems}

    As we all know that calling like this in the render() method is not a good idea but with the fairly simple application, it should be okay to do that.

    Discussion (0)

    pic
    Editor guide