September 26, 2022

How to Loop in React

In this tutorial we'll see how to loop an array in React.

Loop in React JSX using map function

Preferred way in React is to use a map() function to iterate an array.

Syntax of map function is as given below

array.map(function(element, index, arr), thisValue)

Parameters in the map function are-

  1. function- map function calls the specified function once for each element in an array.

    The arguments of the callback function are-

    • element- The current element being processed in the array.
    • index- The index of the current element being processed in the array. This argument is optional.
    • arr- The array map was called upon. This argument is optional.
  2. thisArg- Optional parameter. Value to use as this when executing callbackFn.

You can also use arrow function to define the callback function in the map.

map((element, index, arr) => { /* … */ })

Looping in React example

In the example there is an array of product catalogue which is iterated using map function to render each product item.

// Initial list of products
const productList = [
    { id: 1, name: 'Laptop', price: 455.50 },
    { id: 2, name: 'Mouse', price: 15.89 },
    { id: 3, name: 'USB', price: 10.00 },
    { id: 4, name: 'HDD', price: 55.50 },
];
const Products = () => {

    return (
        <div className="container">
            <ul>
                {productList.map((product) => 
                    <li key={product.id}>{product.id} {product.name} {product.price}</li>
                )}
            </ul>
        </div>
    );
}
export default Products;

On running it, you should see a rendered list of product items.

.	1 Laptop 455.5
.	2 Mouse 15.89
.	3 USB 10
.	4 HDD 55.5

You can also store the array returned by map() function to a variable and then render that array instead. This will help in keeping your JSX clean.

// Initial list of products
const productList = [
    { id: 1, name: 'Laptop', price: 455.50 },
    { id: 2, name: 'Mouse', price: 15.89 },
    { id: 3, name: 'USB', price: 10.00 },
    { id: 4, name: 'HDD', price: 55.50 },
];
const Products = () => {
    const productItems = productList.map((product) => 
        <li key={product.id}>{product.id} {product.name} {product.price}</li>
    );
    return (
        <div className="container">
            <ul>
                {productItems}
            </ul>
        </div>
    );
}

export default Products;

Why key attribute is required

You must have noticed a key attribute being used with value as product id in the above example.

<li key={product.id}>

If you don't use a unique key for each element, you will get a warning

"Warning: Each child in a list should have a unique key prop."

This Key attribute helps React to identify which elements have changed, added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.

The best way to pick a key is to use a string that uniquely identifies a list item among all the other items. Most often you will have unique IDs in your data that can be used as keys.

If the item you're trying to loop through does not have a unique element which can be used as a key, you can use the item index as a key for each iterated item.

// Scenario where products have no IDs
const productItems = productList.map((product, index) => 
     <li key={index}>{product.name} {product.price}</li>
Though use index only as a last resort. As per React documentation-

We don't recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state.

Using forEach to iterate array

Though map() function is the preferred way to iterate an array in React but you do have other choices like forEach, for-of, traditional for loop. Here is an example using forEach to iterate an array.

// Initial list of products
const productList = [
  { id: 1, name: 'Laptop', price: 455.50 },
  { id: 2, name: 'Mouse', price: 15.89 },
  { id: 3, name: 'USB', price: 10.00 },
  { id: 4, name: 'HDD', price: 55.50 },
];
const Products = () => {
  const getProductItems = () => {
    let productItems = [];
    productList.forEach((product) => {
      productItems.push(<li key={product.id}>{product.id} {product.name} {product.price}</li>)
    });
    return productItems;
  };
  return (
    <div className="container">
      <ul>
        {getProductItems()}
      </ul>
    </div>
  );
}

export default Products;

Looping in React to render as Table

Here is another example where the array of products is iterated and each product item is rendered in a table as a table row. Uses react-bootstrap for styling.

import Table from 'react-bootstrap/Table';

// Initial list of products
const productList  = [
    { id: 1, name: 'Laptop', price: 455.50 },
    { id: 2, name: 'Mouse', price: 15.89 },
    { id: 3, name: 'USB', price: 10.00 },
    { id: 4, name: 'HDD', price: 55.50 },
];
const Products = () => {
  return (
    <div className="container">

      <Table striped bordered hover size="sm">
        <thead>
          <tr>
            <th>ID</th>
            <th>NAME</th>
            <th>PRICE</th>
          </tr>
        </thead>
        <tbody>
          {productList.map((product) => 
              <tr key={product.id}>
                  <td>{product.id}</td>
                  <td>{product.name}</td>
                  <td>{product.price}</td>
              </tr>

          )}
        </tbody>
      </Table>
    </div>
  );
}
export default Products;
Loop in React

Keeping in separate component while looping

You may want to have separate component for rendering each iterated element. In that case you should keep the key in the tag for the Component itself.

For example, if there is a separate ProductItem component to render each product item.

ProductItem.js

const ProductItem = (props) => {
  return (
    <tbody>
      <tr>
        <td>{props.item.id}</td>
        <td>{props.item.name}</td>
        <td>{props.item.price}</td>
      </tr>
    </tbody>
  )
}
export default ProductItem;

Products.js

import ProductItem from "./ProductItem";
import Table from 'react-bootstrap/Table';

// Initial list of products
const productList = [
  { id: 1, name: 'Laptop', price: 455.50 },
  { id: 2, name: 'Mouse', price: 15.89 },
  { id: 3, name: 'USB', price: 10.00 },
  { id: 4, name: 'HDD', price: 55.50 },
];
const Products = () => {
  return (
    <div className="container">
      <Table striped bordered hover size="sm">
        <thead>
          <tr>
            <th>ID</th>
            <th>NAME</th>
            <th>PRICE</th>
          </tr>
        </thead>
        {productList.map((val, key) => <ProductItem key={key} item={val} />)}
      </Table>
    </div>
  );
}
export default Products;

As you can see here <ProductItem> tag itself has the key attribute.

<ProductItem key={key} item={val} />

That's all for the topic How to Loop in React. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment