Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 931
johanjohansson Avatar asked Apr 04 '18 07:04

johanjohansson


1 Answers

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> 
like image 153
jevakallio Avatar answered Oct 20 '22 07:10

jevakallio