lcl code base
lcl code base

Reputation: 101

how to write a for loop inside a return statement in react native

so i want to display multiple content on the screen using the for loop and it dose not seem to work. with what i want to do using the map method is not going to work because i don't have an array. here is what i tried.

{() => {
          for (let i = 0; i < cartnumpass; i++) {
            <View style={styles.flyingcard}>
              <View style={styles.amt}>
                <TouchableOpacity>
                  <Icon name="ios-add" type="ionicon" color="#0079b1" />
                </TouchableOpacity>
                <Text style={{fontSize: RFPercentage(2.5)}}>1</Text>
                <TouchableOpacity>
                  <Icon name="ios-remove" type="ionicon" color="#ffaaaa" />
                </TouchableOpacity>
              </View>
              <View style={styles.img}>
                <Image
                  source={require('../resources/Cameras.jpg')}
                  style={styles.image}
                />
              </View>
              <View style={styles.des}>
                <Text style={styles.heading}>Fuhr Camera</Text>
                <Text style={styles.sub}>N 2,000.00 NGN</Text>
                <TouchableOpacity
                  onPress={() => modalfunc(true)}
                  style={{
                    justifyContent: 'space-between',
                    borderColor: '#555',
                    borderWidth: 1,
                    borderStyle: 'solid',
                    width: '90%',
                    alignItems: 'center',
                    flexDirection: 'row',
                    padding: '2%',
                  }}>
                  <Text style={{fontSize: RFPercentage(1.7)}}>
                    Rent Duration
                  </Text>
                  <Icon
                    name="ios-add-circle"
                    type="ionicon"
                    color="#888"
                    size={15}
                  />
                </TouchableOpacity>
              </View>
              <View style={styles.cancel}>
                <TouchableOpacity style={styles.btn}>
                  <Icon name="ios-close" type="ionicon" color="#fff" />
                </TouchableOpacity>
              </View>
            </View>;
          }
        }}

with this code nothing displays on the screen, i don't know if it is possible to write a loop in this form

thanks in advance

Upvotes: 3

Views: 4183

Answers (1)

dave
dave

Reputation: 64657

You wouldn't do it that way, you would do something like:

return new Array(cartnumpass).fill().map((_, index) => {
    <View key={index} style={styles.flyingcard}>
       // ...
    </View>
});

Or you could do something like:

const views = [];
for (let i = 0; i < cartnumpass; i++) {
    views.push(
        <View key={i} style={styles.flyingcard}>
            // ...
        </View>
    );
}
return views;

Upvotes: 4

Related Questions