Start your developer blog today!
Email me

How to Repeat a JSX Element a Variable Number of Times

Published May 8, 2021

Suppose I’m working in React and need to repeat an element n times using JSX.

Let’s say I want to create multiple of these span elements.


But what if the number of elements depends on some variable n?

We know we can map through arrays inside JSX.

[1, 2, 3].map((elem, index) => <span key={index}>dog</span>);

So, we could just create an array of size n and map through that.

const n = 5;
[...Array(n)].map((elem, index) => <span key={index}>dog</span>);

Unfortunately, we can’t simply use Array(n).

Array(n).map((elem, index) => <span key={index}>dog</span>);

Array(n) will create an empty array of length n, while [...Array(n)] will create an array of length n filled with undefined. Therefore, we cannot iterate through Array(n).

More JS Articles