Author avatar

Gaurav Singhal

Iterate Through a JSON Response in JSX Render for React

Gaurav Singhal

  • Sep 25, 2020
  • 7 Min read
  • 264 Views
  • Sep 25, 2020
  • 7 Min read
  • 264 Views
Web Development
Front End Web Development
Client-side Frameworks
React

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.

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

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.

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

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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() {
    // ...
  }
}
jsx

Rendering Data With JSX

Create a component that will render an individual user item.

1
2
3
4
5
6
7
8
9
const User = ({ name, avatar, email }) => (
  <div>
    <img src={avatar} />
    <div>
      <p>{name}</p>
      <p>{email}</p>
    </div>
  </div>
);
jsx

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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>
    );
  }
}
jsx

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.

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

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

1
2
3
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;
js

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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>;
  }
}
jsx

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.

1
2
3
4
5
6
7
8
9
10
11
12
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;
}
js

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.

2