Reputation: 81
I am using material-ui through a project and I am experiencing some small issues with the AutoComplete component when trying to load a bigger list of contacts, some contacts may have the same name (because of test data), but different ids.
{
contact,
key: index,
text: FullName,
value: <MenuItem key={index} primaryText={item} />
}
Thanks,
Upvotes: 2
Views: 7358
Reputation: 1077
some times you have records in mui autocomplete that has the same display property, for example. in a list of users, 2 uers may have the same name. mui auto generates a key based on that property so you get duplicate keys.
the solution is to customize the key. and to do that you need to customize the rendering of the autocomplete list.
use renderOption property
renderOption={(props, option, index) => {
const key = `listItem-${index}-${option.id}`;
return (
<li {...props} key={key}>
{option[optionProperty]}
</li>
);
}}
Upvotes: 6
Reputation: 487
To get rid of the duplicate key warning, the text
property must be unique because this is what's used to create the React ID.
The best thing to do would be to set the 'text' field to the index
or some ID. Let's say the FullName
s are stored in an array. You can then use the index to find the corresponding name. If FullNames are in an object/dictionary, you can retrieve the FullName
s using an ID instead.
When a user clicks on a menu item and the value of the AutoComplete component is not what you want to display to the user, you can dynamically set that property using the onNewRequest
event.
Upvotes: 1