Create N of the same Component/Element in React

avatar
Borislav Hadzhiev

Last updated: Apr 6, 2024
4 min

banner

# Table of Contents

  1. Create N of the same Component/Element in React
  2. Create N of the same Component/Element using a for loop
  3. Concatenate JSX elements into an Array in React
  4. Concatenate JSX elements into an Array using forEach()

# Create N of the same Component/Element in React

To create N of the same Component/Element in React:

  1. Use the Array.from() method to generate an array of N elements.
  2. Replace each element in the array with the actual component.
  3. Render the array of elements.
App.js
function Header() { return <h2>Hello world</h2>; } const App = () => { const threeHeaders = Array.from({length: 3}, (_, index) => { return <Header key={index} />; }); console.log(threeHeaders); return <div>{threeHeaders}</div>; }; export default App;

create n of same component element in react

The code for this article is available on GitHub

The code sample creates an array containing 3 instances of the Header component and renders them.

We used the Array.from() method to generate an array containing 3 elements.

The second parameter the Array.from() method takes is a map function that gets called on every element in the array.

On each iteration, we replace the empty element with an instance of our Header element.

The final result stored in the threeHeaders variable is an array containing 3 instances of the Header component.

We rendered the array of components wrapped in a div, however, that's not necessary.

App.js
function Header() { return <h2>Hello world</h2>; } const App = () => { const threeHeaders = Array.from({length: 3}, (_, index) => { return <Header key={index} />; }); console.log(threeHeaders); // 👇️ Without a wrapper div return threeHeaders; }; export default App;
The code for this article is available on GitHub

An alternative approach is to use a simple for loop.

# Create N of the same Component/Element using a for loop

This is a three-step process:

  1. Declare an empty array that will store the elements.
  2. Use a for loop to iterate N times.
  3. On each iteration, push the element into the array.
App.js
function Header() { return <h2>Hello world</h2>; } const App = () => { const headers = []; const total = 3; for (let index = 0; index < total; index++) { headers.push(<Header key={index} />); } console.log(headers); return <div>{headers}</div>; }; export default App;

create n of same component element using for loop

The code for this article is available on GitHub

This code snippet achieves the same result using a simple for loop.

We loop N times and on each iteration, push a React component into an array.

The last step is to render the array of components.

# Concatenate JSX elements into an Array in React

If you need to concatenate JSX elements into an array:

  1. Initialize an empty array.
  2. Use the push() method to push JSX elements into the array.
  3. Set the key prop on the outermost JSX element to a unique value.
App.js
export default function App() { const fruits = []; fruits.push(<div key="apple">Apple</div>); fruits.push(<div key="banana">Banana</div>); fruits.push(<div key="kiwi">Kiwi</div>); // 👇️ Or if you have an array of strings const names = ['Alice', 'Bob', 'Carl']; const namesJsx = []; names.forEach((name, index) => { namesJsx.push( <div key={index}> <h2>{name}</h2> <hr /> </div>, ); }); return ( <div> <div>{fruits}</div> <br /> <div>{namesJsx}</div> </div> ); }

concatenate jsx elements into array in react

The code for this article is available on GitHub

The first example pushes JSX elements into an array and then renders the array of elements.

We had to set the key prop on each element to a unique value.

App.js
const fruits = []; fruits.push(<div key="apple">Apple</div>); fruits.push(<div key="banana">Banana</div>); fruits.push(<div key="kiwi">Kiwi</div>);

The key prop is used internally by React for performance reasons. It helps the library make sure to only re-render the array elements that have changed.

If the key prop isn't unique, you'd get the Encountered two children with the same key warning.

# Concatenate JSX elements into an Array using forEach()

The second example shows how to iterate over an array of strings using the forEach() method and push a JSX element into a new array on each iteration.

App.js
const names = ['Alice', 'Bob', 'Carl']; const namesJsx = []; names.forEach((name, index) => { namesJsx.push( <div key={index}> <h2>{name}</h2> <hr /> </div>, ); });

The Array.forEach() method can be used when you need to call a function for every element in an array.

However, forEach() can't be used to iterate over an array directly in your JSX code.

The forEach() method calls the provided function with each element in the array but returns undefined.

Using it directly in our JSX code wouldn't make sense because we need to return JSX elements and not undefined.

You can use the forEach() method to:

  1. Iterate over an array.
  2. Push JSX elements into a new array.
  3. Render the JSX elements.
App.js
export default function App() { const names = ['Alice', 'Bob', 'Carl']; const namesJsx = []; names.forEach((name, index) => { namesJsx.push( <div key={index}> <h2>{name}</h2> <hr /> </div>, ); }); return ( <div> <div>{namesJsx}</div> </div> ); }

using foreach method to concatenate jsx elements

The code for this article is available on GitHub

Note that you shouldn't try to access the key property, otherwise, the warning Key is not a prop. Trying to access it will result in undefined is raised.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.