Loop Array in ReactJS

What Is Loop Array In ReactJS

Suppose we have a list (array) data like names, numbers or products, and we want to show all data in react. So we don’t write extra code for each item one by one, We will loop the array using .map() and display them automatically.

Looping allows developers to dynamically generate multiple components and making applications more flexible.

For example, In e-commerce app you want to showing all the products item in display without writing hard-code, It will happen using looping through array.

Example

const fruits = ["Orange", "Strawberry", "Coconut", "Blueberry"];

function FruitList() {
return (
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
);
}

Looping Array Methods In React

React Provides a few JavaScript methods to loop by array. most popular highly recommended method is map().

Other methods like forEach(), for loops and for…of loops are useful but it is less commonly used in React, because these methods don’t directly return arrays of JSX elements but map() is mostly used because it can return JSX elements directly.

1. Using map( ):

When you want to display list of elements, like multiple <div>, <li> or any custom components so you can use map() to generate JSX for each item.

syntax

array.map((item, index) => {
return <p key={index}>{item}</p>;
});
  • In this syntax each item from the array is render into <p> tag using map() function.

Displaying a List of Users

Suppose we have a list of multiple users and we want to display each user’s name and email in list format.

import React from 'react';

function LearnerDirectory() {
const learnerInfo = [
{ uid: 101, fullName: 'poul Roy', contact: 'poul@boxlearn.com' },
{ uid: 102, fullName: 'Mira Choksi', contact: 'mira@boxlearn.com' },
{ uid: 103, fullName: 'Anuj Bakshi', contact: 'anuj@boxlearn.com' }
];

return (
<div>
<h2>Learner Directory</h2>
<ul>
{learnerInfo.map((person) => (
<li key={person.uid}>
{person.fullName} {person.contact}
</li>
))}
</ul>
</div>
);
}

export default LearnerDirectory;

Explanation:

  • The map() method iterate users list data in array.
  • A list item() returned with the users name and email.
  • We use user.id as the key and it is required in React when render list to uniquely identify each item.

2. What Is forEach( ) Array In React

The forEach() method is another way to looping array in JavaScript, but it does not return the new array.

forEach() does not return anything by default, you will have to manually pushing element.

forEach() not ideal for array but it can be useful when you need to perform other task like data manipulation.

Logging User Emails with forEach()

const users = [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' },
{ id: 3, name: 'Alex Brown', email: 'alex@example.com' }
];

users.forEach(user => {
console.log(user.email); // Logs each user's email
});

We are understand one example to why forEach() method not useful for array loop and why map() are the first approach in looping array.

PizzaListCorrect() using map()

function PizzaListCorrect() {
const pizzas = ['Margherita', 'Farmhouse', 'Cheese Burst'];

return (
<ul>
{pizzas.map((pizza) => (
<li>{pizza}</li>
))}
</ul>
);
}

Output in the browser:

<ul>
<li>Margherita</li>
<li>Farmhouse</li>
<li>Cheese Burst</li>
</ul>
  • map() return a new array of <li> elements.
  • React renders them directly inside <ul>.

Map works perfectly in looping

PizzaListWrong() using forEach()

function PizzaListWrong() {
const pizzas = ['Margherita', 'Farmhouse', 'Cheese Burst'];
let result = [];

pizzas.forEach((pizza) => {
result.push(<li>{pizza}</li>);
});

return (
<ul>
{result}
</ul>
);
}

Output in the browser:

<ul>
<li>Margherita</li>
<li>Farmhouse</li>
<li>Cheese Burst</li>
</ul>
  • forEach() will render correctly because you are manually pushing elements to array (result) and then returning it.
  • But it is not recommended, because:
    • forEach() does not return anything by default
    • You will have to create and manage extra array (result) yourself

3. What Is for and for…of Loops In React

Using for…of loops is possible but less uses in react because they require a more manual setup to display JSX elements.

  • Manually create empty array
  • Push JSX into that array
  • Return that array in JSX

Displaying Products with a for Loop

import React from 'react';

function ProductList() {
const products = ['Laptop', 'Phone', 'Tablet'];
const productElements = [];

for (let i = 0; i < products.length; i++) {
productElements.push(<li key={i}>{products[i]}</li>);
}

return (
<div>
<h2>Product List</h2>
<ul>{productElements}</ul>
</div>
);
}

export default ProductList;

In this Example:

  • A for loop is iterate through products.
  • Each product name is pushed into the productElements array, then it will render in UI tag.
  • This method is good but it takes more setup.

4. Complex Data Structures Using map( )

We can use map() in nested array or complex data like Arrays inside arrays or objects inside arrays, this structure are deep and complex so we still use map() for it.

Here the example of complex data List of Products with Nested Details

Learn this example and try yourself:

import React from 'react';

function ProductList() {
const products = [
{ id: 1, name: 'Laptop', price: '$1000', details: { brand: 'Brand A', warranty: '1 year' } },
{ id: 2, name: 'Phone', price: '$600', details: { brand: 'Brand B', warranty: '6 months' } },
{ id: 3, name: 'Tablet', price: '$400', details: { brand: 'Brand C', warranty: '1 year' } }
];

return (
<div>
<h2>Product List</h2>
<ul>
{products.map((product) => (
<li key={product.id}>
<h3>{product.name}</h3>
<p>Price: {product.price}</p>
<p>Brand: {product.details.brand}</p>
<p>Warranty: {product.details.warranty}</p>
</li>
))}
</ul>
</div>
);
}

export default ProductList;

In this example:

  • Each product object contains nested details, like brand and warranty.
  • We use map() to access and render these details within each product’s list item.

Some Basic Tips For Looping Arrays

  1. Always Use Unique Keys: When you using .map() to show lists in React, give each item in unique key (like ID). this help React to track which items were added, removed or changed.
    If you don’t use the keys, React may get confused and re-render incorrectly.
  2. Manage Conditional Rendering: Sometime you only want to show some items in display, instead of all items, you can use .filter() with .map() to pick that item what you want.

Example:

students
.filter(student => student.age >= 18)
.map(student => <p key={student.id}>{student.name}</p>);

This showing only 18 number student and older.

filter() with map() Advanced Example

If you want to display only specific items from array, so you can use filter() with map().

import React from 'react';

function ProductList() {
const products = [
{ id: 1, name: 'Laptop', price: 1000 },
{ id: 2, name: 'Phone', price: 600 },
{ id: 3, name: 'Tablet', price: 400 }
];

return (
<div>
<h2>Products Above $500</h2>
<ul>
{products
.filter((product) => product.price > 500) // Filter products above $500
.map((product) => (
<li key={product.id}>{product.name} - ${product.price}</li>
))}
</ul>
</div>
);
}

export default ProductList;

In this example:

  • The filter() method is include only products priced above $500.

Leave a Comment