How to Write for Loop in React JS

Bernard Bado
December 03, 2021
How to Write for Loop in React JS
When you use affiliate links in this article, We earn a small comission. Thank you!

A JavaScript for loop is a technique that allows you to repeat the same steps on a group of items, usually an array. In React application, for loop can be used in a number of different ways. However, there are 2 preferred methods when it comes to writing for loops in React JS.

There are 2 main ways to write for loops in React JS:

  • Use native Javascript for loop
  • Use array helper methods like map or forEach

In this article, we'll show you how to use JavaScript for loop. We'll also learn how to use both mentioned techniques to write loops in React. And after reading the article, you'll know how to write efficient for loops for your React application.

For Loops in React

When we consider React, It's just a library written in Javascript. This means that on its own, React doesn't have its own for loops. But it also means we can use all types of for loops defined in Javascript language.

Types of for loops in Javascript:

  • for - loops through a block of code a number of times
  • for/in - loops through the properties of an object
  • for/of - loops through the values of an iterable object or array.
note

All of these methods are doing the same thing a bit differently, but they all do the same thing. They are all performing a specific action on a given data multiple times.

Now that we know different types of loops in Javascript, let's look at the example use of each one of them.

info

In the following React example. We want to render a list of users.

Example of for

From all the methods that we'll showcase, this one is the least effective one. It does what it's supposed to do, but it comes with some downsides.

  • It takes quite a bit of code to write.
  • We need to define additional function just to render the output.
App.jsx
const users = [
  { name: "John", age: 24 },
  { name: "Linda", age: 19 },
  { name: "Josh", age: 33 }
];

function App() {

  const renderUsers = () => {
    const result = [];
    for (let i = 0; i < users.length; i++) {
      result.push(<li>{users[i].name}</li>);
    }

    return <ul>{result}</ul>;
  };

  return <div className="App">{renderUsers()}</div>;
}

Example of for/in

This method is a bit more efficient because we don't have to keep track of the index. This loop simply iterates over the whole array and keeps track of the index for us.

App.jsx
const users = [
  { name: "John", age: 24 },
  { name: "Linda", age: 19 },
  { name: "Josh", age: 33 }
];

function App() {

  const renderUsers = () => {
    const result = [];
    for (const userIndex in users) {
      result.push(<li>{users[userIndex].name}</li>);
    }

    return <ul>{result}</ul>;
  };

  return <div className="App">{renderUsers()}</div>;
}

Example of for/of

This method is again a bit more efficient because we don't need the index at all. This loop iterates over the values, so we can directly access the values to render the output. It's definitely an improvement, but we still have to define additional render function.

App.jsx
const users = [
  { name: "John", age: 24 },
  { name: "Linda", age: 19 },
  { name: "Josh", age: 33 }
];

function App() {

  const renderUsers = () => {
    const result = [];
    for (const user of users) {
      result.push(<li>{user.name}</li>);
    }

    return <ul>{result}</ul>;
  };

  return <div className="App">{renderUsers()}</div>;
}

Loops are a convenient way to display a list of items in React. But they come with unnecessary steps, like defining a new variable that holds the result, and then displaying that result.

caution

The loop cycles mentioned above can't be directly used inside render logic. That's why it's important to add an additional render function to your component. In the example above, we used renderUsers for this purpose.

Using Array Helper Methods

In the section before, we showed different examples of looping through the array of users. We did that in order to render the names of users.

In React, it's much more efficient to use array helper methods for this kind of action. We'll show you how in the next example, using the same list of users. And we're gonna do it by using map helper.

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

App.jsx
const users = [
  { name: "John", age: 24 },
  { name: "Linda", age: 19 },
  { name: "Josh", age: 33 }
];

function App() {

  return (
    <div className="App">
      <ul>
        {users.map((user) => (
          <li>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

As you can see, rendering the list with map is much more straightforward, and it doesn't require any additional steps.

tip

It's also possible to chain multiple helper methods. We can use this technique to render only certain parts of a given list.

In the example below, we're using a combination of filter and map to show only users older than 20 years.

The filter method creates a new array with all elements that pass the test implemented by the provided function. (source: MDN)

App.jsx
const users = [
  { name: "John", age: 24 },
  { name: "Linda", age: 19 },
  { name: "Josh", age: 33 }
];

function App () {

  return (
    <div className="App">
      {users
        .filter((user) => user.age > 20)
        .map((user) => (
          <li>{user.name}</li>
        ))}
    </div>
  );
}

Concluding Thoughts

A JavaScript for loop can be used in many different ways. In this article, we discussed the use of for loops in React JS. In particular, we showcased how to use for loops to render a list of items in React.

Needless to say, you learned how to write for loops in React JS. You also learned how to use different types of for loops. And lastly, we showed a more convenient way to render a list of items - array helpers.

Using the following techniques, you can write efficient for loops in React. And more importantly, you can start using for loops like a pro in your React application. 💪