Loop in react-native
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?
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>
)
}
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>
);
}
}