Ishan
Ishan

Reputation: 4028

Autocomplete with custom input in material ui not working

I am able to use the autocomplete by selecting values from the list. Now I want to add a new value in the selection. I tried multiple options including onChange but couldn't implement.

enter image description here

If user types in something and clicks outside the textbox it should convert freetext into a tag. Also, allow user to continue adding more tags from the predefined list/free text.

I am trying out the options here but to no luck. Is this even possible or do I need to look for other options?

Upvotes: 5

Views: 16616

Answers (2)

Matteo Yammine
Matteo Yammine

Reputation: 11

freeSolo allows you to type freely but it does not allow you to register the value as an option ( https://material-ui.com/api/autocomplete/ look for "autoselect" ). Here's the solution:

<Autocomplete
    options={options}
    freeSolo
    autoSelect

Upvotes: 1

Dekel
Dekel

Reputation: 62536

In order to add new items with the Autocomplete you should use the freeSolo property of the Autocomplete. This feature gives you an option to automatically use the value from the input and add it into the value of the Autocomplete.

The issue that you have with the freeSolo is when you have complex objects (and not just strings).

There are multiple ways to solve this.

Option #1 - If the complex objects are only the pre-existing values, you can use this in order to display the correct values:

<Autocomplete
  freeSolo
  getOptionLabel={option => option.title || option}
  ...
/>

If you don't have option.title (which is the case for the default freeSolo because the value is just the text, and not an object) - just show the option.
You can find here a working example: https://codesandbox.io/s/mui-autocomplete-create-complex-4mk5v?file=/demo.js

Option #2 - if you do need complex objects:

You will need to manage adding/removing the objects by yourself.

The onChange prop of the Autocomplete gets a function that you can use for this.

Upvotes: 7

Related Questions