1

I have an array of days, which I am mapping in my View but I am getting warning that Warning: Each child in a list should have a unique "key" prop., I am not able to understand why I am getting this error. I am new to react native, and I am trying to understand what every warning means

my code:

<ScrollView
  horizontal={true}
  showsHorizontalScrollIndicator={false}
  contentContainerStyle={styles.horizontalView}>
  {weekArray.map((item, index) => (
    <TouchableOpacity index={index} onPress={() => setIndexSelect(index)}>
      <Text
        style={{
          fontFamily: "Raleway-Regular",
          fontSize: SizeConfig.blockHeight * 2.1,
          color: indexSelect === index ? COLORS.blackDark : COLORS.blackLight,
        }}>
        {index === weekArray.length - 1 ? ` ${item.day} ` : ` ${item.day} | `}
      </Text>
    </TouchableOpacity>
  ))}
</ScrollView>;
pratteek shaurya
  • 850
  • 2
  • 12
  • 34
  • Check [Understanding unique keys for array children in React.js](https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js) you will get some idea. Basically, you have to define unique key for each view/element in loop – Ravi Jan 20 '21 at 06:45
  • Does this answer your question? [Understanding unique keys for array children in React.js](https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js) – buzatto Jan 20 '21 at 06:59

3 Answers3

7

In react you should pass a unique prop to each component if you are mapping components from an array.

{weekArray.map((item, index) => (
<TouchableOpacity index={index} onPress={() => setIndexSelect(index)} key={index}>
  <Text
    style={{
      fontFamily: "Raleway-Regular",
      fontSize: SizeConfig.blockHeight * 2.1,
      color: indexSelect === index ? COLORS.blackDark : COLORS.blackLight,
    }}>
    {index === weekArray.length - 1 ? ` ${item.day} ` : ` ${item.day} | `}
  </Text>
</TouchableOpacity>

))}

key should be unique for each component.

angelo
  • 2,661
  • 3
  • 16
  • 22
2

That's not an error but a warning. Every time you map over an array in jsx you have to provide a unique key prop. React uses the key prop to create a relationship between the component and the DOM element. The library uses this relationship to determine whether or not the component should be re-rendered.

do something like this:

<TouchableOpacity key={index} onPress={() => setIndexSelect(index)}>
     
Manoj Rawat
  • 312
  • 5
  • 12
0

It is similar to passing an id to objects to recognise them. Similarly here in react-native you need to provide a key which can be a number or anything but different for each component to recognise that and to keep that seperate from others.

In your example you can pass a key at ;

<TouchableOpacity key={index} onPress={() => setIndexSelect(index)}> // If index is different for each component.
Irfan wani
  • 4,084
  • 2
  • 19
  • 34