Is it possible to loop an identical component in Render function?
Something like this:
... onPress = () => { ... }; initialArr = [["blue","text1"],["red","text2"]]; buttonsListArr = []; for (let i = 0; i < initialArr.length; i++) { buttonsListArr.push( <Button style={{borderColor:{initialArr[i][0]}}} onPress={this.onPress.bind(this)}>{initialArr[i][1]}</Button> ); } ... render() { return ( <View style={...}> {buttonsListArr} </View> )};
I mean this is just finite list of components, so any components like ListView/ScrollView etc is not applicable in this particular case. This is just syntax question.
To repeat an element n times with React, we can use the Array function with the map array method. to create an array with 8 span elements with the same content by calling the Array with the n to create an empty array with n slots. Then we use the spread operator to make a copy of it.
To loop through an array of objects in React:Use the map() method to iterate over the array. The function you pass to map() gets called for each element in the array. The method returns a new array with the results of the passed in function.
Using the Array map function is a very common way to loop through an Array of elements and create components according to them in React. This is a great way to do a loop which is a pretty efficient and is a tidy way to do your loops in JSX. It's not the only way to do it, but the preferred way.
You would usually use map for that kind of thing.
buttonsListArr = initialArr.map(buttonInfo => ( <Button ... key={buttonInfo[0]}>{buttonInfo[1]}</Button> );
(key is a necessary prop whenever you do mapping in React. The key needs to be a unique identifier for the generated component)
As a side, I would use an object instead of an array. I find it looks nicer:
initialArr = [ { id: 1, color: "blue", text: "text1" }, { id: 2, color: "red", text: "text2" }, ]; buttonsListArr = initialArr.map(buttonInfo => ( <Button ... key={buttonInfo.id}>{buttonInfo.text}</Button> );
render() { return ( <View style={...}> {initialArr.map((prop, key) => { return ( <Button style={{borderColor: prop[0]}} key={key}>{prop[1]}</Button> ); })} </View> ) }
should do the trick
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