react-nativereact-native-iosreact-native-image

When iterate over a map to show all images, I get warning: Each child in a list should have a unique "key" prop


I have a Map data structure, in which the values of the map contains image uri. I simply want to show all images in the Map.

Here is what I did:

<View style={styles.container}>
{[...imagesMap.values()].map(myImg => {
        const source = {uri: myImg.uri};

        // Warning pointing to here
        return (<Image
          style={{
            width: 50,
            height: 50,
            position: 'absolute',
            left: 62,
            top: 26,
          }}
          source={source}
        />);
      })}
</View>

When running my app on iOS simulator, it shows all images successfully. But I get a warning window on simulator which says Warning: Each child in a list should have a unique "key" prop which I don't understand. I don't have list component at all, but just iterate over values of a map & show images. Why I get that warning?

(The warning message pointing to the line of code where I return the <Image>)


Solution

  • React needs a key prop in order to keep track of the changes of your array elements and rerender the sub components if needed. As you have to make it uniq, consider a good contextual prefix and not a single index as key.

    <View style={styles.container}>
    {[...imagesMap.values()].map((myImg, index) => {
            const source = {uri: myImg.uri};
    
            // Warning pointing to here
            return (<Image
              key={`img-${index}`}
              style={{
                width: 50,
                height: 50,
                position: 'absolute',
                left: 62,
                top: 26,
              }}
              source={source}
            />);
          })}
    </View>