Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ReactJS, can you use a loop in Array.fill?

I'm from a C# background but am new to React and JS in general. I was wondering if there was a way to use lambda functions when declaring an array, for example:

this.state = {
arr: Array(9).fill( (i) => {<Foo index={i} />} ),
};

I'm trying to make an array of React.Components with ascending values in index, and was hoping this would be a viable option.

like image 617
Tom McKeown Avatar asked Jun 02 '18 17:06

Tom McKeown


2 Answers

Not with .fill() alone, as it will just assign rather than invoke the function you give it.

Array(3).fill(() => {}); // [ function, function, function ]

You can use it along with .map(), however, to accomplish this. The iterator function you provide will be given the index as the 2nd argument (using _ as a throwaway variable for the 1st).

Array(9).fill(0).map((_, i) => <Foo index={i} />)

Using both is necessary because Array(9) only assigns the array's length, leaving the indexes unassigned.

'length' in Array(9) // true
0 in Array(9) // false

While .fill() will work with unassigned indexes, .map() specifically will ignore them.


You can also use Array.from() instead, which accepts the same iterator as .map().

Array.from(Array(9), (_, i) => <Foo index={i} />)

Also, with it, the 1st argument doesn't necessarily have to be an Array:

Array.from({ length: 9 }, (_, i) => <Foo index={i} />)
like image 112
Jonathan Lonowski Avatar answered Oct 04 '22 03:10

Jonathan Lonowski


Probably something like this:

this.state = {
  arr: new Array(5).map((emptyElement, index) => <Foo index={index} />);
}
like image 42
Tomasz Mularczyk Avatar answered Oct 04 '22 04:10

Tomasz Mularczyk