How can I add unique keys to React/Material UI Autocomplete component?

You can define your own renderOption that can return the list item with a correct key value. Your code complains about the duplicated keys because by default, Autocomplete uses the getOptionLabel(option) to retrieve the key:

<Autocomplete
  renderOption={(props, option) => {
    return (
      <li {...props} key={option.id}>
        {option.name}
      </li>
    );
  }}
  renderInput={(params) => <TextField {...params} label="Movie" />}
/>

If it still doesn’t work, check your props order, you need to declare the key prop last, if you put it before the props provided by the callback:

<Box component="li" key={key} {...props}

Then it will be overridden by the props.key from MUI. It should be like this:

<Box component="li" {...props} key={key}

Live Demo

Codesandbox Demo

Leave a Comment