Last updated: Apr 6, 2024
Reading time·4 min
for
loopTo create N of the same Component/Element in React:
Array.from()
method to generate an array of N elements.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.
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.
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;
An alternative approach is to use a simple for loop.
for
loopThis is a three-step process:
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.
If you need to concatenate JSX elements into an array:
push()
method to push JSX elements into the array.key
prop on the outermost JSX element to a unique value.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> ); }
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.
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.
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.
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.
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:
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> ); }
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.
You can learn more about the related topics by checking out the following tutorials: