javascriptlistreact-nativebackground-coloralternate

create a loop or play with states for alternating background


I have a list, and I would like to change the background color of the items in the list. Basically, to increase the contrast and have a nicer rendering, I would like to change the background from one product out of two.

For that I wanted to use this:

backgroundColor: item.id % 2 === 0 ? '#fde3a7' : '#FFF'

it works but the problem is that my ids are not necessarily in order, so it gives me:

screencap

However, I do not know how to apply it for one in two products. My idea would be to pass as a parameter a variable which increments with each loop or use a state, so for example that at each position, the background changes (even position: white background, odd position background orange for example)

On the other hand, I have this idea in mind but I'm a little lost on how to achieve it.

I don't know if I expressed myself well and if you understood my problem. In any case, thank you for any help given.

The whole code of the list :

const Item = ({ item, onPress, style }) => (
  <ListItem
    style={{width:'100%'}}
    containerStyle= {{backgroundColor: item.id % 2 === 0 ? '#fde3a7' : '#FFF'}}
    bottomDivider
    onPress={() => this.props.navigation.navigate('ProductDetails', {productId:parseInt(item.id)})}>
    <ListItem.Content style={{flexDirection: 'row', justifyContent: 'space-between'}}>
      <Image //source={{uri: URL + item.photo.["_1_"].url}} style={{ width: 25, height: 25}}
      />
      <ListItem.Title style={{width: '65%', fontSize: 16}}>{ ( item.name.length > 20 ) ? item.name.substring(0, 20) + ' ...'  :  item.name}</ListItem.Title>
      <ListItem.Subtitle style={{ color: '#F78400', position: "absolute", bottom: 0, right: 0 }}>{item.cost}{i18n.t("products.money")}</ListItem.Subtitle>
    </ListItem.Content>
  </ListItem>
);

Solution

  • You can work with the index param you get from the renderItem method (FlatList) instead of item.id

    renderItem({ item, index, separators });
    

    Extend your renderItem method by index and pass the index via the props to the ListItem