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.
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} />)
Probably something like this:
this.state = {
arr: new Array(5).map((emptyElement, index) => <Foo index={index} />);
}
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