Skip to content

Contact sales

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

How to Implement a Component Loop in React

Jul 16, 2020 • 6 Minute Read

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 :

      return(
	<>
	{data}
	</>
)
    

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.

      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;
    

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:

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

Finally, output this array as:

      <ul>
     {items.map((item,index)=>{
         return <li key={index}>{item}</li>
     })}
 </ul>
    

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

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

Then render that single array instead.

      function App() {
  return (
    <>
      <h2>This is a simple list of items</h2>
      <ul>
        {itemList}
      </ul>
    </>
  );
}
    

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

      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;
    

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.

      import React,{useState} from 'react';
import './App.css';

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

export default App;
    

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

      npm install axios
    

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.

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

Next, populate the state with data from the server.

      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);
      })
 },[])
    

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

      return (
    <>
    {userData.map((data,id)=>{
      return <div key={id}>
        <h2>{data.first_name} {data.last_name}</h2>
        <p>{data.email}</p>
      </div>
    })}

    </>
  );
}
    

Finally, separate out the logic from your template.

      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}

    </>
  );
}
    

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.

Learn More

Explore these React courses from Pluralsight to continue learning: