I am listing products by using FlatList in the app. I have Products.js, ProductCard.js.
Products.js:
const Products = ({navigation}) => {
const renderItem = ({item}) => (
<ProductCard
item={item}
onClickHandler={() => navigation.navigate('Item Detail', {item: item})}
/>
);
return (
<View>
<ProductOperations />
<FlatList
data={data}
keyExtractor={item => item.id.toString()}
renderItem={renderItem}
/>
</View>
);
};
export default Products;
ProductCard.js:
const ProductCard = props => {
const createStars = rating => {
//...logic
};
return (
<TouchableOpacity key={props.item.id} style={styles.card} onPress={props.onClickHandler} >
<Image style={styles.image} source={{uri: props.item.thumbnail}} />
<View style={styles.textColumn}>
<Text style={[styles.brandText, styles.textPadding]}>
{props.item.brand}
</Text>
<Text style={[styles.titleText, styles.textPadding]}>
{props.item.title}
</Text>
</View>
<View style={styles.textColumn}>
<View style={[styles.textColumn, styles.textPadding]}>
{createStars(props.item.rating)}
</View>
<Text style={[styles.ratingText, styles.textPadding]}>
{props.item.rating}
</Text>
</View>
<Text style={[styles.priceText, styles.textPadding]}>
${props.item.price}
</Text>
</TouchableOpacity>
);
};
export default ProductCard;
I have keyExtractor on the FlatList, and key on the ProductCard. But I get warning:
Warning: Each child in a list should have a unique "key" prop.
Check the render method of `ProductCard`. See https://reactjs.org/link/warning-keys for more information.
at Icon (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.shoppingapp&modulesOnly=false&runModule=true:101233:38)
How can I solve this? What should I change?
2
Answers
It means you need to have a
key
for elements created inside an array, which I believe comes fromcreateStars
, sample solution:Agree with @AngYC !
I think you can also remove the key props on TouchableOpacity in your ProductCard component.