Create N of the same Component/Element in React

avatar

Borislav Hadzhiev

Tue Apr 19 20222 min read

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;

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.fromk 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 wrapper div return threeHeaders; }; export default App;

An alternative approach is to use a simple for loop.

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

  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;

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.