'material-ui autocomplete duplicate key warning
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.
- Warning when passing an object as a dataSource item. I get a duplicate key warning: "Warning: flattenChildren(...): Encountered two children with the same key"
{
contact,
key: index,
text: FullName,
value: <MenuItem key={index} primaryText={item} />
}
- When typing the rendering is slow, because sometimes it matches a lot of contacts. Ideally I would like to show maximum 5-10 contacts in the autocomplete, but that is not possible yet. (that feature seems to be accepted in a PR already, or?)
Thanks,
Solution 1:[1]
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>
);
}}
Solution 2:[2]
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 FullNames 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 FullNames 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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Safi Habhab |
| Solution 2 | John William Domingo |
