Author avatar

Gaurav Singhal

How to Implement a Component Loop in React

Gaurav Singhal

  • Jul 16, 2020
  • 6 Min read
  • 118 Views
  • Jul 16, 2020
  • 6 Min read
  • 118 Views
Web Development
Front End Web Development
Client-side Framework
React

Introduction

React allows you to easily write JavaScript code inside your components. This makes it easy for any developer to comfortably handle common programming techniques in React, such as looping through a set of items, creating and invoking functions, storing data in local variables, and so on.

This guide demonstrates how to implement loops in common use cases, such as rendering a list of static data and outputting data from an API.

Outputting Arrays in JSX

Component loops are regular JavaScript loops combined with some JSX. A great feature of JSX is that it allows you to output arrays directly on the DOM. This means that if you have an array named data, you can output its elements on the DOM as shown below :

1
2
3
4
5
return(
	<>
	{data}
	</>
)
jsx

Thus you can push your data along with its supporting HTML inside an array and then output that array inside your component's return statements enclosed in curly braces. There are several JavaScript loops that you can use for this purpose. Since map() is the most popular and easiest one, this guide extensively uses it in the examples.

Rendering Static Data

Consider a simple use case where you have to render a list of items on the DOM.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import React from 'react';
import './App.css';

function App() {
  return (
    <>
      <h2>This is a simple list of items</h2>
      <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
        <li>Item 5</li>
      </ul>
    </>
  );
}

export default App;
jsx

Certainly rendering each <li> would be cumbersome and time-consuming, as shown above. The best practice is to break down the repeating segment of your code and push it in an array. For instance, each <li> tag can be seen as a repeating segment, and hence you can create an array containing the following data:

1
let items=['Item 1','Item 2','Item 3','Item 4','Item 5'];
jsx

Finally, output this array as:

1
2
3
4
5
 <ul>
     {items.map((item,index)=>{
         return <li key={index}>{item}</li>
     })}
 </ul>
jsx

Further, you can clean up your JSX by pushing the entire HTML in an array:

1
2
3
let itemList=items.map((item,index)=>{
  return <li key={index}>{item}</li>
})
jsx

Then render that single array instead.

1
2
3
4
5
6
7
8
9
10
function App() {
  return (
    <>
      <h2>This is a simple list of items</h2>
      <ul>
        {itemList}
      </ul>
    </>
  );
}
jsx

Alternately, the same can be done using the forEach() method, as shown below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import React from 'react';
import './App.css';


let items=['Item 1','Item 2','Item 3','Item 4','Item 5'];
let itemList=[];
items.forEach((item,index)=>{
  itemList.push( <li key={index}>{item}</li>)
})
function App() {
  
  return (
    <>
   
      <h2>This is a simple list of items</h2>
      <ul>
        {itemList}
      </ul>
    </>
  );
}

export default App;
jsx

You can try out the above method using a regular for loop, and it wwill work the same. As your component grows larger in size, segmenting code away from your UI makes it cleaner, modular, and readable, and therefore easy to debug.

Rendering Dynamic Data

In another practical scenario, you'd typically get data from a backend that you would store inside your component's state and then loop over it to output that data on the page. Let's say you want to fetch a list of users for your web app.

Import useState and create a simple state variable to hold an array of objects.

1
2
3
4
5
6
7
8
9
10
11
import React,{useState} from 'react';
import './App.css';

function App() {
  const [userData,setUserData]=useState([])
  
    </>
  );
}

export default App;
jsx

To make API calls, install axios by running the following command in your root directory:

1
npm install axios
shell

Since the page needs to be fully loaded with data as soon as it's requested on the frontend, the data must be populated when the component mounts the first time on the DOM. This can be done using the lifecycle hook useEffect() by passing an empty array as the second parameter.

1
2
3
  useEffect(()=>{
	//make an API call when component first mounts
  },[])
javascript

Next, populate the state with data from the server.

1
2
3
4
5
6
7
8
9
10
useEffect(()=>{
    axios.get('https://reqres.in/api/users?page=2')
      .then(res=>{
        console.log(res.data.data);
        setUserData(res.data.data)
      })
      .catch(err=>{
        console.log(err);
      })
 },[])
jsx

Using map(), cycle through the data and display it on the page.

1
2
3
4
5
6
7
8
9
10
11
12
 return (
    <>
    {userData.map((data,id)=>{
      return <div key={id}>
        <h2>{data.first_name} {data.last_name}</h2>
        <p>{data.email}</p>
      </div>
    })}

    </>
  );
}
jsx

Finally, separate out the logic from your template.

1
2
3
4
5
6
7
8
9
10
11
12
13
  const users=userData.map((data,id)=>{
    return <div key={id}>
      <h2>{data.first_name} {data.last_name}</h2>
      <p>{data.email}</p>
    </div>
  })
  return (
    <>
    {users}

    </>
  );
}
jsx

Conclusion

Using component loops to output and manipulate data is a common development method in React. It allows you to group HTML elements with dynamic data together, as shown in this guide. This would generally be impossible to do in a pure JavaScript app without DOM queries. You should use component loops to output sets of items in a clean, efficient, and readable manner.

1