The for Loop in React

Irakli Tchigladze Jan 30, 2023
  1. Implement for Map With the .map() Method in React
  2. JavaScript for Loop
  3. Immediately Invoked Function
The for Loop in React

Dealing with complex back-end data is a part of the front-end developer’s job. Often, the data includes a list of objects that represent components or other building blocks for the UI.

For instance, when creating an online store, the data will likely contain the list of products that need to appear on the website. Manually going over the list and creating components one by one is inefficient for multiple reasons. For example, what will you do if a product is removed or added to the list? You can’t go back and update your JSX file every time.

There are multiple ways to go over the list and render components or HTML elements automatically.

Implement for Map With the .map() Method in React

The .map() method, introduced in ES6, is the default way to loop over an array and return a valid JSX element that contains data from each item in the array. Developers often use this method to create custom components as well as regular HTML elements.

Even though there are other ways to perform a loop, most React developers use .map() method because it’s easy to read, write and maintain. Here’s how to loop over an array of objects and render user data to the screen:

class App extends Component {
  render() {
    const data = [{name: "John Doe", "age": 44}, {name:"Jane Doe", "age": 45}]
    console.log('App started');
    return <div>
    {data.map(person => <p key={person.name}>{`${person.name}, ${person.age} years old`}</p>)}
    </div>
  }
}

Output:

John Doe, 44 years old

Jane Doe, 45 years old

Remember that the map() method will run twice in this example and return one paragraph element each time. That’s why it is essential to wrap its results with a <div></div>. Every component must return one parent container, having as many child elements as you’d like.

key Attribute

Keep in mind that every element created using the .map() method must have a key identifier, set to a unique value.

<p key={person.name}>{}</p>)

React does not recommend using the index value to generate a unique value for the key property.

Passing Down props

If you’re going to use the .map() method to render multiple components, you can also pass down the props.

Let’s say we’re trying to render multiple Product components. Here’s how we would pass the props:

return <div>
    {data.map(product => <Product price={product.price} name={product.name}></Product>)}
    </div>

JavaScript for Loop

Another way to loop over an array is to use the for loop. If you choose this approach, you must perform the loop above the return block.

Here’s how the code would look like:

class App extends Component {
  render() {
    const data = [{name: "John Doe", "age": 44}, {name:"Jane Doe", "age": 45}]
    let persons = [];
    for (let i = 0; i<data.length; i++){
      persons.push(<p>{data[i].name + ", " + data[i].age + " years old"}</p>)
    }
    return <div>
    {persons}
    </div>
  }
}

Compared to .map(), this approach is more verbose and harder to understand. However, the results would be the same.

Immediately Invoked Function

It’s technically possible to use the for loop in your return statement, but you’d have to create a function and use the for loop as the body. Once you’re done writing the function, you should follow it with brackets () to immediately call it. Here’s how it would work:

class App extends Component {
  render() {
    const data = [{name: "John Doe", "age": 44}, {name:"Jane Doe", "age": 45}]
    return 
    <div>
    {function() {
      let persons = []
    for (let i = 0; i<data.length; i++){
      persons.push(<p>{data[i].name + ", " + data[i].age + " years old"}</p>)
    }
    return persons
    }()
    }</div>
  }
}
Irakli Tchigladze avatar Irakli Tchigladze avatar

Irakli is a writer who loves computers and helping people solve their technical problems. He lives in Georgia and enjoys spending time with animals.

LinkedIn

Related Article - React Loop