Liviu Ignat
Liviu Ignat

Reputation: 81

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.

  1. 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} />
    }
  1. 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,

Upvotes: 2

Views: 7358

Answers (3)

Cristiano Mendon&#231;a
Cristiano Mendon&#231;a

Reputation: 1282

Autocomplete now supports the getOptionKey param.

Upvotes: 2

Safi Habhab
Safi Habhab

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

John William Domingo
John William Domingo

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 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.

Upvotes: 1

Related Questions