Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS Array fill with key in JSX element

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

like image 350
Hasanavi Avatar asked Apr 05 '18 16:04

Hasanavi


People also ask

What is key attribute in JSX?

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 element []?

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.

Can we use array index as a key 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.


1 Answers

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.

like image 149
T.J. Crowder Avatar answered Oct 26 '22 01:10

T.J. Crowder