Leem.fin
Leem.fin

Reputation: 42622

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>)

Upvotes: 0

Views: 40

Answers (2)

jbg
jbg

Reputation: 116

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>

Upvotes: 1

Erhan Bi&#231;er
Erhan Bi&#231;er

Reputation: 122

When creating a list in the UI from an array with JSX, you should add a key prop to each child and to any of its’ children.

Example <Text key={"uniqueID"} >Item</Text>

you should use this

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

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

Upvotes: 0

Related Questions