I'm looking for the shortest approach to generate multiple JSX element.
For example, if I need to generate 10 <span>
I can easily use Array map function
{[...Array(10)].map((x, i) =>
<span key={i} ></span>
)}
There's nothing wrong with the above approach but I want another shorter version like,
Array(10).fill(<span></span>);
However, React will shout about not having the unique 'key' props. does anyone have a clean solution without using the random()?
I'm looking for the shortest approach to generate multiple JSX element.
For example, if I need to generate 10 <span>
I can easily use Array map function
{[...Array(10)].map((x, i) =>
<span key={i} ></span>
)}
There's nothing wrong with the above approach but I want another shorter version like,
Array(10).fill(<span></span>);
However, React will shout about not having the unique 'key' props. does anyone have a clean solution without using the random()?
Share Improve this question edited Apr 5, 2018 at 16:28 Hasanavi asked Apr 5, 2018 at 16:26 HasanaviHasanavi 8,6252 gold badges31 silver badges36 bronze badges1 Answer
Reset to default 14The Array(10).fill(<span></span>);
solution has more problems than just the key: It uses the same span for each entry in the array, which is presumably not what you want.
You can use Array#from
:
Array.from({length:10}, (_, i) => <span key={i}></span>);
// or
Array.from(Array(10), (_, i) => <span key={i}></span>);
It still uses a callback, but you're going to need that no matter what. It's slightly less verbose, and more efficient (not that it matters in 99.999% of cases), than the spread-and-map.