Rendering a dynamic amount of elements in React Native

Rendering a dynamic amount of elements in React Native

Imagine this scenario: you're aiming to render a precise number of squares for crafting a pattern or generating some kind of chart. When the quantity is relatively small, you can easily render it like this:

return (
    <View>
        <Square />
        <Square />
        <Square />
        <Square />
    </View>
)

And now, you have four squares. However, what if the number of squares is too large or dynamically changing? In such cases, rendering without utilising a loop becomes impractical.

To achieve this, leverage the Array constructor method provided in JavaScript, specifying the desired array length as its argument. Following this, employ the spread operator within brackets to deconstruct the array.

console.log([...Array(5)])
// [undefined, undefined, undefined, undefined, undefined]

We're not fussing over what's the value; our main aim is just to whip up an array with a set number of items. After that, we'll map it out. Easy as pie!

return (
    <View>
        {[...Array(100)].map((_, index) => (
            <Square key={index} />
        ))}
    </View>
)

Et voilá, a 100 squares.