How to Loop Through an Array in React.JS

This article will guide you on how to loop through an array in React.JS and render it effectively. In React.JS, you often need to loop through arrays to render lists of elements dynamically. Whether it’s a list of items, user-generated content, or API data, you can easily loop through an array and display it using JSX.

1. Setting Up the React Environment

Before we start, ensure you have a React environment set up. You can create a new React app using Create React App:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npx create-react-app my-app
cd my-app
npm start
npx create-react-app my-app cd my-app npm start
npx create-react-app my-app
cd my-app
npm start

This will set up a new React project and start the development server.

2. Basic Syntax for Looping in React

In React, we use JavaScript to manipulate arrays, and the most common method for looping through arrays is map(). This method allows us to iterate over an array and return a new array of JSX elements.

Here’s the basic syntax of using map() in React:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
array.map((item, index) => {
return ;
});
array.map((item, index) => { return ; });
array.map((item, index) => {
  return ;
});

item: The current element in the array.
index: The index of the current element in the array (optional, but helpful for assigning unique keys).
Element: JSX represents the item.

3. Rendering Arrays Using map()

React’s JSX allows us to directly use the map() function to iterate over an array and return elements for each item in the array.

Example: Looping Through an Array of Strings
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import React from 'react';
function App() {
const fruits = ['Apple', 'Banana', 'Orange', 'Pineapple'];
return (
<div>
<h1>List of Fruits</h1>
<ul>
<li style="list-style-type: none;">
<ul>
<li style="list-style-type: none;">
<ul>
<li style="list-style-type: none;">
<ul>{fruits.map((fruit, index) => (
<li>{fruit}</li>
</ul>
</li>
</ul></li>
</ul>
</li>
</ul>
))}
</div>
); } export default App;
import React from 'react'; function App() { const fruits = ['Apple', 'Banana', 'Orange', 'Pineapple']; return ( <div> <h1>List of Fruits</h1> <ul> <li style="list-style-type: none;"> <ul> <li style="list-style-type: none;"> <ul> <li style="list-style-type: none;"> <ul>{fruits.map((fruit, index) => ( <li>{fruit}</li> </ul> </li> </ul></li> </ul> </li> </ul> ))} </div> ); } export default App;
import React from 'react';

function App() {
  const fruits = ['Apple', 'Banana', 'Orange', 'Pineapple'];
  return (

List of Fruits

 
        • {fruits.map((fruit, index) => (
        • {fruit}
))}
); } export default App;

fruits.map((fruit, index) => ...): Loops through the fruits array.
<li key={index}>{fruit}</li>:Renders each fruit inside a list item (<li>), using index as the key.

4. Key Prop for List Items

Each child element must have a unique

prop when rendering a list in React. It key helps React identify which items have changed, been added, or removed, which enhances performance during re-rendering.

Important Note: It is recommended to use a unique identifier (such as an ID) instead of the index if your array items might change order or if the array is dynamic.

Example with Unique Key:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const fruits = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Orange' },
{ id: 4, name: 'Pineapple' }
];
function App() {
return (
<div>
<h1>List of Fruits</h1>
<ul>
<li style="list-style-type: none;">
<ul>
<li style="list-style-type: none;">
<ul>
<li style="list-style-type: none;">
<ul>{fruits.map(fruit => (
<li>{fruit.name}</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
))}
</div>
); }
const fruits = [ { id: 1, name: 'Apple' }, { id: 2, name: 'Banana' }, { id: 3, name: 'Orange' }, { id: 4, name: 'Pineapple' } ]; function App() { return ( <div> <h1>List of Fruits</h1> <ul> <li style="list-style-type: none;"> <ul> <li style="list-style-type: none;"> <ul> <li style="list-style-type: none;"> <ul>{fruits.map(fruit => ( <li>{fruit.name}</li> </ul> </li> </ul> </li> </ul> </li> </ul> ))} </div> ); }
const fruits = [
  { id: 1, name: 'Apple' },
  { id: 2, name: 'Banana' },
  { id: 3, name: 'Orange' },
  { id: 4, name: 'Pineapple' }
];
function App() {
  return (

List of Fruits

        • {fruits.map(fruit => (
        • {fruit.name}
))}
); }

In this example, each fruit has an id property, which we use as a unique key prop.

5. Example: Loop Through an Array of Objects

If you’re working with an array of objects, you can use map() to loop through the array and render the properties of each object.

Example: Rendering an Array of Objects
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import React from 'react';
function App() {
const users = [
{ id: 1, name: 'Alice', age: 30 },
{ id: 2, name: 'Bob', age: 25 },
{ id: 3, name: 'Charlie', age: 35 }
];
return (
<div>
<h1>User List</h1>
<ul>
<li style="list-style-type: none;">
<ul>
<li style="list-style-type: none;">
<ul>
<li style="list-style-type: none;">
<ul>{users.map(user => (
<li>{user.name} - {user.age} years old</li>
</ul>
</li>
</ul></li>
</ul>
</li>
</ul>
))}
</div>
); } export default App;
import React from 'react'; function App() { const users = [ { id: 1, name: 'Alice', age: 30 }, { id: 2, name: 'Bob', age: 25 }, { id: 3, name: 'Charlie', age: 35 } ]; return ( <div> <h1>User List</h1> <ul> <li style="list-style-type: none;"> <ul> <li style="list-style-type: none;"> <ul> <li style="list-style-type: none;"> <ul>{users.map(user => ( <li>{user.name} - {user.age} years old</li> </ul> </li> </ul></li> </ul> </li> </ul> ))} </div> ); } export default App;
import React from 'react';
function App() {
  const users = [
    { id: 1, name: 'Alice', age: 30 },
    { id: 2, name: 'Bob', age: 25 },
    { id: 3, name: 'Charlie', age: 35 }
  ];
  return (

User List

        • {users.map(user => (
        • {user.name} - {user.age} years old
))}
); } export default App;

In this example:
We loop through the users array, which contains objects with id, name, and age properties.
We use user.id as the key, and we render both the name and age properties inside the list item.

6. Rendering Dynamic Data in Lists

Your data might come from an API or user input in real-world applications. In these cases, you can loop through arrays dynamically.

Example: Fetching Data from an API
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import React, { useState, useEffect } from 'react';
function App() {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => setPosts(data));
}, []);
return (
<div>
<h1>Posts</h1>
<ul>
<li style="list-style-type: none;">
<ul>
<li style="list-style-type: none;">
<ul>
<li style="list-style-type: none;">
<ul>{posts.map(post => (
<li>
<h3>{post.title}</h3>
{post.body}</li>
</ul>
</li>
</ul></li>
</ul>
</li>
</ul>
))}
</div>
); } export default App;
import React, { useState, useEffect } from 'react'; function App() { const [posts, setPosts] = useState([]); useEffect(() => { fetch('https://jsonplaceholder.typicode.com/posts') .then(response => response.json()) .then(data => setPosts(data)); }, []); return ( <div> <h1>Posts</h1> <ul> <li style="list-style-type: none;"> <ul> <li style="list-style-type: none;"> <ul> <li style="list-style-type: none;"> <ul>{posts.map(post => ( <li> <h3>{post.title}</h3> {post.body}</li> </ul> </li> </ul></li> </ul> </li> </ul> ))} </div> ); } export default App;
import React, { useState, useEffect } from 'react';
function App() {
  const [posts, setPosts] = useState([]);
  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => response.json())
      .then(data => setPosts(data));
  }, []);
  return (

Posts

        • {posts.map(post => (
        • {post.title}

          {post.body}
))}
); } export default App;

Here:
We use useState() to manage the posts state.
useEffect() fetches data from an API (jsonplaceholder.typicode.com) and updates the state with the response.
We then loop through the posts array and render each post’s title and body.

Conclusion

Looping through arrays in React is a simple yet powerful concept that enables dynamic rendering of lists and data. By using JavaScript’s map() Combined with JSX, you can render arrays efficiently and handle dynamic data such as user input or API responses.

Always use a unique key prop when rendering lists.
Make sure your data is well-structured and handled appropriately.
Consider performance optimizations, especially when rendering large lists.
With these tips, you should be able to loop through arrays in ReactJS like a pro!

 

Also Read:-

How To Create custom post type (CPT) in WordPress

WordPress Error Handling by Hooks3

Email Notifications in Laravel

Leave a Reply