I am rendering several list items from an api:
{clientSurveys &&
clientSurveys?.map(({ data }, index) => (
<ListItem
key={data?.SurveyID}
component={Link}
to={`survey/${data?.SurveyID}`}
disablePadding
sx={{ color: 'inherit' }}
>
)}
As seen above, I am providing a key (which is the id of the survey in this case):
key={data?.SurveyID}
Why am I keep getting this warning?
Warning: Each child in a list should have a unique "key" prop.
CodePudding user response:
Why am I keep getting this warning?
The optional chaining (?
) in your key
value suggests that the data
might be undefined, so there's a chance that a couple of your items are getting the same key with undefined
value.
key={data?.SurveyID} // it may end up with "undefined" value
You have to secure this case when data
is undefined
.
Its also worthy to mention that using the optional chaining in the key
value is rather an anti pattern, because the key
should be static and unique. data?.SurveyID
also suggests that it might change over time.