Anjali
Anjali

Reputation: 2698

Alternate colors in FlatList

How can I alternate colors in FlatList? I tried the following example, but I could not get this to work.

Below is my code:

_renderItem = ({ item, index }) => {
  var geodist = require("geodist");
  var dist = geodist(
    { lat: item.cLat, lon: item.cLong },
    { lat: item.LatL, lon: item.Long2 },
    "mi"
  );
  return (
    <View style={{ color: index % 2 === 0 ? "red" : "green" }}>
      <Text style={styles.Address1}>{item.addr} </Text>

      <TouchableOpacity
        onPress={() => {
          this.handleClick(`tel:${item.phone}`);
        }}
      >
        <Image
          source={require("../images/call.png")}
          style={styles.actionImage}
        />
      </TouchableOpacity>
      <Text style={styles.Address1}>{item.phone}</Text>
      <View style={styles.sepBoxes}>
        <View style={[styles.box, styles.box1]}>
          <View style={styles.AddressRow}>
            {item.Online != "" ? (
              <TouchableOpacity onPress={() => Linking.openURL(item.Online)}>
                <Image
                  source={require("../images/www-icon.png")}
                  style={styles.actionImage1}
                />
              </TouchableOpacity>
            ) : null}
            <Text style={styles.underLineTextOnline}> Online</Text>
            <TouchableOpacity onPress={() => Linking.openURL(destUrl)}>
              <Text style={styles.underLineText}>Directions</Text>
            </TouchableOpacity>

            <Text style={styles.AddressSpace}>Miles:{dist}</Text>
          </View>
        </View>
      </View>

      <View />
    </View>
  );
};

Upvotes: 1

Views: 1431

Answers (1)

Tholle
Tholle

Reputation: 112787

renderItem has index in the object that is passed as first argument, so you can use that to alternate the color.

Example

_renderItem = ({ item, index }) => (
  <View style={{ color: index % 2 === 0 ? 'red' : 'green' }}>
    <Text>Hello World!</Text>
  </View>
);

Upvotes: 3

Related Questions