Why I get this error Message?
Warning: Each child in a list should have a unique "key" prop.
import * as React from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Image, Dimensions, Animated, FlatList } from 'react-native';
const StoryProfile = () => {
const dataStory = [
{
type: 'NORMAL',
item: {
id: '1',
image: 'https://picsum.photos/200',
}
},
{
type: 'NORMAL',
item: {
id: '2',
image: 'https://picsum.photos/200',
}
},
{
type: 'NORMAL',
item: {
id: '3',
image: 'https://picsum.photos/200',
}
},
{
type: 'NORMAL',
item: {
id: '4',
image: 'https://picsum.photos/200',
}
},
{
type: 'NORMAL',
item: {
id: '5',
image: 'https://picsum.photos/200',
}
},
{
type: 'NORMAL',
item: {
id: '6',
image: 'https://picsum.photos/200',
}
},
];
const Item = React.memo(({ image }) => {
return (
<View>
<Image source={{uri: image}} height={48} width={48} resizeMode="contain" />
</View>
)
});
const renderItem = ({ item }) => {
return (
<Item image={item.image} />
)
};
return (
<View style={styles.container}>
<FlatList
data={dataStory}
keyExtractor={item => item.id}
key={Math.random(1000)}
renderItem={renderItem}
/>
</View>
)
};
const styles = StyleSheet.create({
container: {
flex: 1
}
})
export default StoryProfile;
I have tried a key prop but thats not working. What I am doing wrong ?
………………………………………………………………………………………………………………………………………………………………………………………………
>Solution :
- No need to have a key prop on a FlatList component:
<FlatList
data={dataStory}
keyExtractor={item => item.id}
key={Math.random(1000)} {/* No need to have a key attribute on FlatList */}
renderItem={renderItem}
/>
- When you add a keyExtractor={item => item.id}, it will search the id on each object of your dataStory, which is undefined in your case, so the key in your case is the same undefined.
So, the first solution is:
- Instead of having:
{
type: 'NORMAL',
item: {
id: '1',
image: 'https://picsum.photos/200',
}
}
You should have this:
{
id: '1',
type: 'NORMAL',
item: {
image: 'https://picsum.photos/200',
}
}
- The second solution is to change the keyExtractor to be:
keyExtractor={item => item.item.id}
or:
keyExtractor={({item}) => item.id}