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.
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
:
1return(
2 <>
3 {data}
4 </>
5)
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.
Consider a simple use case where you have to render a list of items on the DOM.
1import React from 'react';
2import './App.css';
3
4function App() {
5 return (
6 <>
7 <h2>This is a simple list of items</h2>
8 <ul>
9 <li>Item 1</li>
10 <li>Item 2</li>
11 <li>Item 3</li>
12 <li>Item 4</li>
13 <li>Item 5</li>
14 </ul>
15 </>
16 );
17}
18
19export 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:
1let items=['Item 1','Item 2','Item 3','Item 4','Item 5'];
Finally, output this array as:
1 <ul>
2 {items.map((item,index)=>{
3 return <li key={index}>{item}</li>
4 })}
5 </ul>
Further, you can clean up your JSX by pushing the entire HTML in an array:
1let itemList=items.map((item,index)=>{
2 return <li key={index}>{item}</li>
3})
Then render that single array instead.
1function App() {
2 return (
3 <>
4 <h2>This is a simple list of items</h2>
5 <ul>
6 {itemList}
7 </ul>
8 </>
9 );
10}
Alternately, the same can be done using the forEach()
method, as shown below.
1import React from 'react';
2import './App.css';
3
4
5let items=['Item 1','Item 2','Item 3','Item 4','Item 5'];
6let itemList=[];
7items.forEach((item,index)=>{
8 itemList.push( <li key={index}>{item}</li>)
9})
10function App() {
11
12 return (
13 <>
14
15 <h2>This is a simple list of items</h2>
16 <ul>
17 {itemList}
18 </ul>
19 </>
20 );
21}
22
23export 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.
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.
1import React,{useState} from 'react';
2import './App.css';
3
4function App() {
5 const [userData,setUserData]=useState([])
6
7 </>
8 );
9}
10
11export default App;
To make API calls, install axios
by running the following command in your root directory:
1npm 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.
1 useEffect(()=>{
2 //make an API call when component first mounts
3 },[])
Next, populate the state with data from the server.
1useEffect(()=>{
2 axios.get('https://reqres.in/api/users?page=2')
3 .then(res=>{
4 console.log(res.data.data);
5 setUserData(res.data.data)
6 })
7 .catch(err=>{
8 console.log(err);
9 })
10 },[])
Using map()
, cycle through the data and display it on the page.
1 return (
2 <>
3 {userData.map((data,id)=>{
4 return <div key={id}>
5 <h2>{data.first_name} {data.last_name}</h2>
6 <p>{data.email}</p>
7 </div>
8 })}
9
10 </>
11 );
12}
Finally, separate out the logic from your template.
1 const users=userData.map((data,id)=>{
2 return <div key={id}>
3 <h2>{data.first_name} {data.last_name}</h2>
4 <p>{data.email}</p>
5 </div>
6 })
7 return (
8 <>
9 {users}
10
11 </>
12 );
13}
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.
Explore these React courses from Pluralsight to continue learning: