Reputation: 960
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>;
Upvotes: 1
Views: 11504
Reputation: 5095
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.
Upvotes: 0
Reputation: 312
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)}>
Upvotes: 2
Reputation: 2961
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.
Upvotes: 6