johanjohansson
johanjohansson

Reputation: 541

How do I alternate colors in Flat List (React Native)

Trying to alternate colors in React Natives Flatlist. I believe I need rowID or something similar to do it. This is what I've got so far:

let colors = ['#123456', '#654321', '#fdecba', '#abcdef'];


<View >
    <FlatList style={{backgroundColor: colors[this.index % colors.length]}}

      data={this.state.dataSource}
      renderItem={({item}) => <Text style={styles.listStyle}>{item.title}, {item.releaseYear}</Text>}
      keyExtractor={(item, index) => index}
    />
  </View> 

Any ideas?

Upvotes: 10

Views: 10265

Answers (1)

jevakallio
jevakallio

Reputation: 35890

The renderItem callback argument has a property index that allows you to access the row index for the current row:

<View >
  <FlatList
    data={this.state.dataSource}
    keyExtractor={(item, index) => index}
    renderItem={({item, index}) => (
      <View style={{ backgroundColor: colors[index % colors.length] }}>
        <Text style={styles.listStyle}>{item.title}, {item.releaseYear}</Text>
      </View>
    )}
  />
</View> 

Upvotes: 23

Related Questions