Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Iterate Through a JSON Response in JSX Render for React

Building scalable apps requires handling and displaying JSON responses. This guide covers how to loop over an array of objects and render each item's information.

Sep 25, 2020 • 7 Minute Read

Introduction

One of the advantages of React is that you can quickly generate HTML chunks using the JSX template system. Looping and presenting the data is a ubiquitous part of building apps with React. Iterating over an array of objects and rendering the data with JSX is one of the most fundamental and crucial things you need to be able to do before moving on to a real-world project.

When building scalable web apps, you will have to handle JSON responses and display them on a web page. This guide will teach you how to loop over an array of objects and render each item's information in React.

Fetching Data Using fetch()

The first step is to fetch data from an external service. For this example, you can use the Random Users API, which will generate a list of random users.

To fetch data from the service, use the browser's native fetch API. Pass the external URL to the fetch method and it will return a promise, so you need to chain the then() methods.

      let users = [];
fetch(`https://randomuser.me/api/?results=10`)
  .then((res) => res.json())
  .then((data) => {
    console.log(data.results);
  });
    

If you do not want to chain the then() methods, you can use the async-await syntax. Wrap the fetch call in a function and place the async keyword before the function definition. Inside the method, use the await keyword to get the results.

      async function getRandomUsers() {
  const res = await fetch(`https://randomuser.me/api/?results=10`);
  const data = await res.json();
  return data.results;
}
    

More details on the fetch API are discussed in this guide.

Now, create a React component that will fetch random users when the component is mounted. Ideally, the fetch call should be placed in the componentDidMount lifecycle method so the results are ready once the component gets mounted on the page. Once you retrieve the results from fetch, store the user list in the component's state.

      class UserList extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      users: [],
    };

    this.getRandomUsers = this.getRandomUsers.bind(this);
  }

  async getRandomUsers() {
    const res = await fetch(`https://randomuser.me/api/?results=10`);
    const data = await res.json();
    return data.results;
  }

  async componentDidMount() {
    const users = await this.getRandomUsers();
    this.setState({ users });
  }

  render() {
    // ...
  }
}
    

Rendering Data With JSX

Create a component that will render an individual user item.

      const User = ({ name, avatar, email }) => (
  <div>
    <img src={avatar} />
    <div>
      <p>{name}</p>
      <p>{email}</p>
    </div>
  </div>
);
    

Next, iterate over the data using the map() or forEach() methods or using loops.

Using the map() Method

The map() method is the most commonly used function to iterate over an array of data in JSX. You can attach the map() method to the array and pass a callback function that gets called for each iteration. When rendering the User component, pass a unique value to the key prop. The key prop helps React keep track of JSX elements and identify any changes in the array.

      class UserList extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      users: [],
    };

    // ...
  }

  // ...

  render() {
    return (
      <div>
        {this.state.users.map((user) => (
          <User
            name={`${user.name.first} ${user.name.last}`}
            avatar={user.picture.thumbnail}
            email={user.email}
            key={user.id.value}
          />
        ))}
      </div>
    );
  }
}
    

Using the Traditional for Loop

Alternatively, you can also use regular loops like the for loop to render JSX elements.

Create a separate function called renderUsers() in the component. Initialize an empty array to which you push the JSX element for each user.

Run the for loop from index 0 to the length of the user state array.

      for (let i = 0; i < this.state.users.length; i++) {
  // ...
}
    

Then, inside the loop body, access the current user as follows:

      let name = `${this.state.users[i].name.first} ${this.state.users[i].name.last}`;
let avatar = this.state.users[i].picture.thumbnail;
let email = this.state.users[i].email;
    

Let's put all this together in the component. Inside the render() method, call the renderUser() method to display the list of users.

      class UserList extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      users: [],
    };

    this.renderUsers = this.renderUsers.bind(this);

    // ...
  }

  function renderUsers() {
      const userList = [];
      for(let i = 0; i < this.state.users.length; i++) {
          let name = `${this.state.users[i].name.first} ${this.state.users[i].name.last}`;
          let avatar = this.state.users[i].picture.thumbnail;
          let email = this.state.users[i].email;
          let key = this.state.users[i].id.value;
          userList.push(<User name={name} avatar={avatar} email={email} key={key}/>);
      }

      return userList;
  }

  // ...

  render() {
    return <div>{this.renderUsers()}</div>;
  }
}
    

As you can see, the renderUsers() method is hard to read; writing such code is generally avoided as it is difficult to debug and maintain.

Using the forEach() Method

To make the renderUsers() method more readable, use the forEach method, as shown below. Its usage is similar to the map() method, but the forEach() method does not return anything. This makes it unusable directly inside the render() method, as you need an array to store the individual JSX elements.

      function renderUsers() {
  const userList = [];
  this.state.users.forEach((user) => {
    let name = `${user.name.first} ${user.name.last}`;
    let avatar = user.picture.thumbnail;
    let email = user.email;
    let key = user.id.value;
    userList.push(<User name={name} avatar={avatar} email={email} key={key} />);
  });

  return userList;
}
    

Conclusion

As a developer, you must understand your use case and curate solutions according to your requirements. In most cases, the map() method gets the job done, but it is good to know additional ways of looping over an array of JSON. Also, don't forget to add a key prop unique to the JSX element to help with performance.