React is all about reusability. You can define a component’s structure, appearance and reuse it. You can pass props to customize component’s content and even appearance.

In this article, we will explore how to use forEach() to loop over an array of objects, automatically create and render components for every object in the array.

Using forEach() to create components in React

It’s not uncommon to have website data formatted as an array of objects.

For example, an array where each item is an object that contains information about a product. We can use forEach() to create a component for every product, passing it different bits of data to customize their content.

To do this, we need to follow three steps:

  • Create an empty array
  • Call forEach() method on array of objects (or other values which you are going to use as source of data for components).
  • As first argument, pass a callback function that creates a component and adds it to a new array.

Let’s look at an example:

const fruits = [
    { variety: "apple", price: 20 },
    { variety: "pear", price: 5 },
    { variety: "grape", price: 15 }
  ];
const fruitComponents = [];
  fruits.forEach((fruit) => {
    fruitComponents.push(
      <Fruit fruit={fruit.variety} price={fruit.price}></Fruit>
    );
  })

As you can see, we create an array fruitComponents.

Then use the forEach() method to perform a side effect for every object in the array. Then use the push() method to add a custom <Fruit> component to a newly created empty array.

We take object data and pass it as props to the <Fruit> component.

forEach() will create a new component for every item in the original array and add it to fruitComponents array.

Finally, you can render all these components in JSX. Simply reference name of the components array.

export default function App() {
  const fruits = [
    { variety: "apple", price: 20 },
    { variety: "pear", price: 5 },
    { variety: "grape", price: 15 }
  ];
  const fruitComponents = [];
  fruits.forEach((fruit) => {
    fruitComponents.push(
      <Fruit fruit={fruit.variety} price={fruit.price}></Fruit>
    );
  });
  return <div className="App">{fruitComponents}</div>;
}

Don’t forget to wrap JavaScript expressions embedded in JSX with curly braces.

Go to CodeSandbox to see live demo.

How to use forEach() in JSX

It’s important to remember that forEach() method does not return anything. It works similar to a for loop. forEach() iterates over every item in the array, and ‘does something’ with every item.

forEach() to loop over array of objects to render components

We can use forEach() to create and render components for every object in the array, but we must do it outside of JSX.

Personally, I prefer to keep JSX simple and readable. Creating an array of components outside of JSX is not a problem.

Using forEach() to loop over an array of objects and create components

First argument to forEach() is the callback function, which specifies ‘what to do’ for each item in the array.

As React developers, often we need to create components for every object in the array.

We can define a callback function that takes object property values and passes them as props (or children) to React components.

Let’s look at an example:

import Fruit from "./Fruit";
export default function App() {
  const fruits = [
    { variety: "apple", price: 20 },
    { variety: "pear", price: 5 },
    { variety: "grape", price: 15 }
  ];
  const fruitComponents = [];
  fruits.forEach((fruit) => {
    fruitComponents.push(
      <Fruit fruit={fruit.variety} price={fruit.price}></Fruit>
    );
  });
  return <div className="App">{fruitComponents}</div>;
}

In this case, we have an array of objects named fruits. Each object in the array contains fruit information.

We use the push() method to add <Fruit> components to a newly created array. The child component displays object data, passed down via props.

Check out live demo on CodeSandbox.

forEach() vs map() to create components in JSX

There are differences and similarities between two methods.

Let’s start with similarities. First argument to both forEach() and map() is a callback function that specifies ‘what to do’ with each item in the array.

A big difference is that map() modifies every item in the array, adds modified items (components) to a new array, and returns the array of components. Therefore you can embed map() directly in JSX.

On the other hand, forEach() does not return anything. It only performs a side effect.

Basically forEach() ‘does something’ to every item in the array. We use the callback function (first argument) to specify what to do. However, you can still use this functionality to create an array of components.

Simply create an empty array. Then pass forEach() a callback function that creates a component, and adds that component to the new array.

const fruits = [
    { variety: "apple", price: 20 },
    { variety: "pear", price: 5 },
    { variety: "grape", price: 15 }
  ];
  const fruitComponents = [];
  fruits.forEach((fruit) => {
    fruitComponents.push(
      <Fruit fruit={fruit.variety} price={fruit.price}></Fruit>
    );
  })

You can render all components in JSX. Simply reference name of the array in JSX.

<div className="App">{fruitComponents}</div>

Check out live CodeSandbox demo. Explore and play with code yourself.

Can you use forEach() to return a component?

Technically, no. By design, forEach() method does not return any value. However, it performs a side-effect.

You can apply forEach() to an array of objects and use data from every object to create a component and add it to a new array.

Then you can render the array of components in JSX.