Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop and render elements in React-native?

Tags:

react-native

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.

like image 796
Stich Avatar asked Feb 28 '17 22:02

Stich


People also ask

How do you repeat a component in react native?

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.

How do you repeat over array and create elements in React?

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.

How do you loop over a component in React?

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.


2 Answers

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> ); 
like image 73
nbkhope Avatar answered Oct 23 '22 16:10

nbkhope


render() {   return (     <View style={...}>        {initialArr.map((prop, key) => {          return (            <Button style={{borderColor: prop[0]}}  key={key}>{prop[1]}</Button>          );       })}      </View>   ) } 

should do the trick

like image 24
Damathryx Avatar answered Oct 23 '22 16:10

Damathryx