简体   繁体   中英

React Native FlatList: render conditional style with dynamic data

I am new to React native and implementing FlatList where I am facing some issues with dynamic data. I have a list of total seats and booked seats.

    this.state = {
        seats: props.route.params.seats, 
        reservedSeats: props.route.params.Reserved,
        date: new Date() 
    }

Following is the FlatList i have implemented

      <FlatList style={styles.flatListArea1} 
           contentContainerStyle={{margin:0}}
           data={this.state.seats}
           numColumns={4}
                        
           showsHorizontalScrollIndicator={false} 
           renderItem={({item}) => 
                            
              <View style={styles.containerIcons} key={item}>
                  <TouchableOpacity style={this.state.selectedItem === item ? styles.menuSelected : styles.menuTop }  onPress={ () => this.selectSeat(item)}>
                      <View style={styles.buttons}>
                        <Text style={styles.HallsText} key={item.key}>{item.Id}</Text>
                      </View>
                  </TouchableOpacity>
              </View>}
       />

On Click event, I am able to change the color. I appreciate if someone can help to understand, How we can re-render FlatList based on dynamic data presented in reserved state. For example. for today, out of 5 seats 3 are booked. Those should be gray and others should be red.

I appreciate your help on this.

Regards,

You firstly need a method that tells if a seat is available or not.

isReserved = (item) => {
 return this.state.reservedSeats.filter(seat => seat.Id ==item.Id).length > 0;
}

Then you change the appearance of your list like this

<FlatList
  style={styles.flatListArea1}
  contentContainerStyle={{ margin: 0 }}
  data={this.state.seats}
  numColumns={4}
  showsHorizontalScrollIndicator={false}
  renderItem={({ item, index }) => (
    <View style={[styles.containerIcons, { backgroundColor: isReserved(item) ? "#FAFAFA" : "white" }]} key={index}>
        <TouchableOpacity
            style={this.state.selectedItem === item ? styles.menuSelected : styles.menuTop}
            onPress={() => this.selectSeat(item)}
            disabled={isReserved(item)}
        >
            <View style={styles.buttons}>
                <Text
                    style={[styles.HallsText, { backgroundColor: isReserved(item) ? "#CCC" : "white" }]}
                    key={item.key}
                >
                    {item.Id}
                </Text>
            </View>
        </TouchableOpacity>
    </View>
)}
/>;

Pay attention to the key attribute

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM