Home > other >  React Native FlatList: render conditional style with dynamic data
React Native FlatList: render conditional style with dynamic data

Time:03-12

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,

CodePudding user response:

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

  • Related