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()?
According to the react documentation: A key is a special string attribute you need to include when creating lists of elements. Keys help react identify which elements have changed, have been deleted or added. It gives the elements in the array a stable identity.
What is JSX? JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React.
Warn if an element uses an Array index in its key . The key is used by React to identify which items have changed, are added, or are removed and should be stable. It's a bad idea to use the array index since it doesn't uniquely identify your elements.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With