Loop in react-native

React Native

React Native Problem Overview


I want to make a list of fields depending on the number of the player that user has selected. I wanted to make something like this:

generatePaymentField() {
	var noGuest = this.state.guest;
	var payment = 
	<View>
		<View>
			<View><Text>No</Text></View>
			<View><Text>Name</Text></View>
			<View><Text>Preference</Text></View>
		</View>;
		
	for (var i=0; i < noGuest; i++) {
		payment = payment + 
			<View>
				<View>
					<TextInput />
				</View>
				<View>
					<TextInput />
				</View>
				<View>
					<TextInput />
				</View>
			</View>;
	}
	return payment;
}

render () {
	var payment = this.generatePaymentField();
	this.setState({payment : payment});
	return (
		<View>
			{this.state.payment}
		</View>;
	)
}

But react-native regarded the syntax above as 'unexpected token' pointing at the for loop line. Is there any other way I can achieve doing this?

React Native Solutions


Solution 1 - React Native

This should work

render(){

	var payments = [];

	for(let i = 0; i < noGuest; i++){

		payments.push(
			<View key = {i}>
				<View>
					<TextInput />
				</View>
				<View>
					<TextInput />
				</View>
				<View>
					<TextInput />
				</View>
			</View>
		)
	}
	
	return (
		<View>
			<View>
				<View><Text>No</Text></View>
				<View><Text>Name</Text></View>
				<View><Text>Preference</Text></View>
			</View>

			{ payments }
		</View>
	)
}

Solution 2 - React Native

render() {
var myloop = [];

for (let i = 0; i < 10; i++) {
  myloop.push(
    <View key={i}>
    <Text>{i}</Text>
    </View>
  );
}

 return (
      
        <View >
          <Text >Welcome to React Native!</Text>
           {myloop}
        </View>
       
      
    );
  }
}

Solution 3 - React Native

render() { var myloop = [];

for (let i = 0; i < 10; i++) {
  myloop.push(
    <View key={i}>
    <Text style={{ textAlign: 'center', marginTop: 5 }} >{i}</Text>
    </View>
  );
}

 return (

        <View >
          <Text >Welcome to React Native!</Text>
           {myloop}
        </View>


    );
  }

Output 1 2 3 4 5 6 7 8 9

Solution 4 - React Native

First of all, I recommend writing the item you want to render multiple times (in your case list of fields) as a separate component:

function Field() {
    return (
        <View>
            <View>
                <TextInput />
            </View>
            <View>
                <TextInput />
            </View>
            <View>
                <TextInput />
            </View>
        </View>
    );
}

Then, in your case, when rendering based on some number and not a list, I'd move the for loop outside of the render method for a more readable code:

renderFields() {
    const noGuest = this.state.guest;
    const fields = [];
    for (let i=0; i < noGuest; i++) {
        // Try avoiding the use of index as a key, it has to be unique!
        fields.push(
            <Field key={"guest_"+i} />
        );
    }
    return fields;
}

render () {
    return (
        <View>
            <View>
		        <View><Text>No</Text></View>
		        <View><Text>Name</Text></View>
		        <View><Text>Preference</Text></View>
	        </View>
            {this.renderFields()}
        </View>;
    )
}

However, there are many more ways to render looped content in react native. Most of the ways are covered in this article, so please check it out if you're interested in more details! The examples in article are from React, but everything applies to React Native as well!

Solution 5 - React Native

You can create render the results (payments) and use a fancy way to iterate over items instead of adding a for loop.

const numberOfGuests = 3;

Array(numberOfGuests).fill(noGuest).map(guest => console.log(guest));

Example:

renderPayments(numberOfGuests) {
  return Array(numberOfGuests).fill(numberOfGuests).map((guest, index) => {
    return(
      <View key={index}>
        <View><TextInput /></View>
        <View><TextInput /></View>
        <View><TextInput /></View>
	  </View>
    );
  }
}

Then use it where you want it

render() {
  return(
     const { guest } = this.state;
     ...
     {this.renderPayments(guest)}
  );
}

Hope you got the idea.

If you want to understand this in simple Javascript check Array.prototype.fill()

Solution 6 - React Native

renderItem(item)
  {
    const width = '80%';
    var items = [];

	for(let i = 0; i < item.count; i++){

		items.push( <View style={{ padding: 10, borderBottomColor: "#f2f2f2", borderBottomWidth: 10, flexDirection: 'row' }}>
    <View style={{ width }}>
      <Text style={styles.name}>{item.title}</Text>
      <Text style={{ color: '#818181', paddingVertical: 10 }}>{item.taskDataElements[0].description + " "}</Text>
      <Text style={styles.begin}>BEGIN</Text>
    </View>

    <Text style={{ backgroundColor: '#fcefec', padding: 10, color: 'red', height: 40 }}>{this.msToTime(item.minTatTimestamp) <= 0 ? "NOW" : this.msToTime(item.minTatTimestamp) + "hrs"}</Text>
  </View> )
  }

  return items;
}

render() {
return (this.renderItem(this.props.item)) 
}

Solution 7 - React Native

render(){

	var payments = [];

	for(let i = 0; i < noGuest; i++){

		payments.push(
			<View key = {i}>
				<View>
					<TextInput />
				</View>
				<View>
					<TextInput />
				</View>
				<View>
					<TextInput />
				</View>
			</View>
		)
	}
	
	return (
		<View>
			<View>
				<View><Text>No</Text></View>
				<View><Text>Name</Text></View>
				<View><Text>Preference</Text></View>
			</View>

			{ payments }
		</View>
	)
}

Solution 8 - React Native

render(){

	var payments = [];

	for(let i = 0; i < noGuest; i++){

		payments.push(
			<View key = {i}>
				<View>
					<TextInput />
				</View>
				<View>
					<TextInput />
				</View>
				<View>
					<TextInput />
				</View>
			</View>
		)
	}
	
	return (
		<View>
			<View>
				<View><Text>No</Text></View>
				<View><Text>Name</Text></View>
				<View><Text>Preference</Text></View>
			</View>

			{ payments }
		</View>
	)
}

render(){

	var payments = [];

	for(let i = 0; i < noGuest; i++){

		payments.push(
			<View key = {i}>
				<View>
					<TextInput />
				</View>
				<View>
					<TextInput />
				</View>
				<View>
					<TextInput />
				</View>
			</View>
		)
	}
	
	return (
		<View>
			<View>
				<View><Text>No</Text></View>
				<View><Text>Name</Text></View>
				<View><Text>Preference</Text></View>
			</View>

			{ payments }
		</View>
	)
}

render(){

	var payments = [];

	for(let i = 0; i < noGuest; i++){

		payments.push(
			<View key = {i}>
				<View>
					<TextInput />
				</View>
				<View>
					<TextInput />
				</View>
				<View>
					<TextInput />
				</View>
			</View>
		)
	}
	
	return (
		<View>
			<View>
				<View><Text>No</Text></View>
				<View><Text>Name</Text></View>
				<View><Text>Preference</Text></View>
			</View>

			{ payments }
		</View>
	)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKelvin AliyantoView Question on Stackoverflow
Solution 1 - React NativevinayView Answer on Stackoverflow
Solution 2 - React NativeKaran KJView Answer on Stackoverflow
Solution 3 - React NativeKeshav GeraView Answer on Stackoverflow
Solution 4 - React NativeNesha ZoricView Answer on Stackoverflow
Solution 5 - React NativeabranheView Answer on Stackoverflow
Solution 6 - React NativeApurva AggarwalView Answer on Stackoverflow
Solution 7 - React Nativedhyan tannaView Answer on Stackoverflow
Solution 8 - React NativeAnshif yaseenView Answer on Stackoverflow