Reputation: 63
I keep getting this warning "each child in a list should have unique 'key' prop" even though I have unique items with different keys.
Whenever I create a new 'plant' object I give it a new uuid
setPlants(prevItems => {
return [
{name: newPlantName, key: uuid.v4(), timeInterval: null},
...prevItems,
];
And my listItem component is set up with a key
<ListItem
key={plant.key}
Whenever I print my list all the 'keys' have a different uuid. The warning occurs every time I refresh the app so it might be somehow because i'm using a database to access the data? I'm not really sure but I am using mmkv to store the data from my state and then I show that data when the app first opens.
This is the full mapping:
{plants &&
plants.map(plant =>
plant ? (
<PlantItem
plant={plant}
deletion={openDeleteOrCancel}
setPlants={setPlants}
/>
) : null,
)}
PlantItem component:
return (
<>
<ActionSheet
visible={actionSheetVisible}
closeOverlay={() => {
setActionSheetVisible(false);
}}
actions={actions}
/>
<ListItem
key={plant.key}
onPress={() => {
setActionSheetVisible(true);
}}
bottomDivider>
<ListItem.Content key={plant.key} style={styles.listItemContainer}>
<ListItem.Title>{plant.name}</ListItem.Title>
{/* <Icon name="check" size={20} /> */}
</ListItem.Content>
</ListItem>
{showAddTimeInterval && (
<AddTimeInterval
createTimeInterval={createTimeInterval}
closeModal={toggleShowAddTimeInterval}
plantName={plant.name}
/>
)}
</>
);
This is how my states are initiated
const [plantsStorage, setPlantsStorage] = useStorage('plantss');
const [plants, setPlants] = useState(plantsStorage ? plantsStorage : []);
useEffect(() => {
setPlantsStorage(plants);
});
The warning is just really annoying, if there is no way to change my code to fix it is there a way to mute it somehow? just for this specific warning not all warnings.
Upvotes: 3
Views: 4209
Reputation: 202917
The React key should be used on the outermost mapped element.
React Lists and Keys
{plants.map(plant =>
plant ? (
<PlantItem
key={plant.key} // <-- use key here!
plant={plant}
deletion={openDeleteOrCancel}
setPlants={setPlants}
/>
) : null,
)}
Suggestion, filter the plants
array to remove the null "holes".
{plants
.filter(Boolean) // include only truthy plant objects
.map(plant => (
<PlantItem
key={plant.key} // <-- use key here!
plant={plant}
deletion={openDeleteOrCancel}
setPlants={setPlants}
/>)
)}
Upvotes: 6