Home > Software engineering >  MUI 5 Autocomplete choose attribute of object as value
MUI 5 Autocomplete choose attribute of object as value

Time:06-02

My options looks like this

const options = [
  {
    "VaccinationType": "Sample"
  },
  {
    "VaccinationType": "Another Sample"
  }
]

Code:

const [vacType, setVacType] = useState('');

<Autocomplete
    value={vacType}
    onChange={(e, value) => {
        console.log(value);
        setVacType(value);
    }}
    options={options}
    getOptionLabel={(option) => option.VaccinationType}
    isOptionEqualToValue={(option, value) => option.VaccinationType === value.VaccinationType}
    renderInput={(params) => (
            <TextField
                {...params}
                variant="outlined"
                size="small"
            />
    )}
/>

I tried logging my value it still outputs the object { VaccinationType: "Sample" }. I want it to only output "Sample"

In MUI 4 I'm using this getOptionSelected={(option, value) => option?.VaccinationType === value?.VaccinationType}

CodePudding user response:

Autocomplete options care about the item of the array which you put. According to your code, each item has all object values. I searched to find a way but I couldn't.

There is a way probably you already thought;

You can edit options parameter like options={options.map(o => o.VaccinationType)} and remove VaccinationType key on getOptionLabel and isOptionEqualToValue

<Autocomplete
    value={vacType}
    onChange={(e, value) => {
      console.log(value);
      setVacType(value);
  }}
    options={options.map(o => o.VaccinationType)}
    getOptionLabel={(option) => option}
    isOptionEqualToValue={(option, value) =>
      option === value
    }
    renderInput={(params) => (
      <TextField {...params} variant="outlined" size="small" />
    )}
  />

CodePudding user response:

I don't know why you want to do that!,
You can simply use value object wherever you want, and use any key of the object, take the value object as it's then use value.VaccinationType.

But, if you want to do this:

<Autocomplete
    {...props}
    value={options.find(op => op.VaccinationType === vacType)}
    onChange={(e, value) => {
        console.log(value);                   //Result: { "VaccinationType": "Sample" }
        setVacType(value.VaccinationType);    // <==== Here, add `.VaccinationType`
    }}
/>
  • Related