10

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()?

1 Answer 1

14

The 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.

Sign up to request clarification or add additional context in comments.

8 Comments

i don't see much diff between suggested answer and [...Array(10)].map((x, i) => <span key={i} ></span> ) :P, because op was trying to skip the loop
@MayankShukla: Right, there isn't. The main point here is that the apparent simplicity of Array#fill is illusory, one will need a callback.
@mayank one iteration instead of two?
Thanks, Ideally I would like to avoid key here if possible as it's just for CSS animation purpose. but wondering if there's any shorter version for this dumb job.
@JonasW., i think yes :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.