Search code examples
reactjsreact-nativereact-native-flatlist

Prevent Item Background Color From Changing Flatlist


I have a FlatList that is pulling in contact from a user's phone. I want to give each contact that doesn't have an avatar a random color from an array of hex color codes which I call "CircleColors".

This is what I'm trying:

 <FlatList
          data={filteredContacts}
          renderItem={({ item }) => (
            <View key={uuidv4()} style={styles.contactItem}>
              <View style={item.avatar && styles.contactAvatar}>
                {item.avatar && (
                  <Image
                    style={{
                      borderRadius: 50,
                      width: 50,
                      height: 50,
                    }}
                    source={{
                      uri: item.avatar,
                    }}
                  />
                )}
                {!item.avatar && (
                  <ContactItem
                    itemData={item.name}
                    color={
                      CircleColors[
                        Math.floor(Math.random() * CircleColors.length)
                      ]
                    }
                  />
                )}
              </View>
              <View>
                <Text style={styles.contactTxt}>{`${item.name}`}</Text>
                <Text
                  style={
                    item.usernames.length
                      ? styles.contactUser
                      : styles.noUser
                  }
                >
                  {item.usernames.length ? `$${item.usernames}` : null}
                </Text>
              </View>
            </View>
          )}
        />

And here is the code for the contact item:

const ContactItem = ({ itemData, color }) => {
return (
  <View
    style={[
      styles.userCircle,
      {
        backgroundColor: color,
      },
    ]}
  >
    <Text style={styles.userCircleTxt}>
      {itemData.substr(0, 1).toUpperCase()}
    </Text>
  </View>
);

};

The problem is that on scroll, the flatlist rerenders each item, and the colors change each time. Is there a way to persist the original random color given to each item background, even on scroll?

Any help would be greatly appreciated.

Thanks!


Solution

  • the problem come with this line

    <View key={uuidv4()} style={styles.contactItem}>
    

    the key always change, you should pass index to key

    renderItem={({ item,index }) => (
        <View key={index} style={styles.contactItem}>