How to Repeat a JSX Element "N" Number of Times
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.
<span>dog</span>
<span>dog</span>
<span>dog</span>
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)
.