'How to make MUI's Autocomplete display the label from the matching value in props.options?

I have a multilingual website where there are certain Autocompletes whose options array need to have its items labels translated, which is done very easily.

However, it would be harder to update the current chosen value, stored elsewhere. Since Autocomplete uses the label from the value prop instead of using the item of same ID within options, it ends up like this:

enter image description here

const vehicles = [
  { id: 1, label: "Car" },
  { id: 2, label: "Bus" }
];

const currentVehicleValue = {
  id: 2,
  label: "Ônibus"
};

export default function ComboBox() {
  return (
    <Autocomplete
      disablePortal
      id="combo-box-demo"
      options={vehicles}
      value={currentVehicleValue}
      renderInput={(params) => <TextField {...params} label="Vehicle" />}
    />
  );
}

Is there a way to just tell Autocomplete to use the label inside the options prop instead of the one within the value

demo

EDIT: I mean to have the label within options being shown while I don't type anything. As in, the language changed, the options were translated, but the currentValue was not, so it would be nice to have the Autocomplete use the label from the matching item within options as long as I don't type anything.



Solution 1:[1]

Edit after clarification

You can change how the <TextField/> is rendered by tweaking the props it receives.

In the example below, I find the currentVehicle by its id and change the inputProps.value to be the vehicle label.

Also, to ensure MUI finds the currentValue correctly within the options, you will need to use the isOptionEqualToValue to compare the options ids instead of strict equality

const vehicles = [
  { id: 1, label: "Car" },
  { id: 2, label: "Bus" }
];

const currentVehicleValue = {
  id: 2,
  label: "Ônibus"
};

function compareValueToOption(option, value) {
  return option.id === value.id;
}

function ComboBox() {
  return (
    <Autocomplete
      disablePortal
      id="combo-box-demo"
      options={vehicles}
      value={currentVehicleValue}
      renderInput={ComboBoxInput}
      isOptionEqualToValue={compareValueToOption}
    />
  );
}

function ComboBoxInput(props) {
  const currentVehicle = vehicles.find(
    (vehicle) => vehicle.id === currentVehicleValue.id
  );
  props.inputProps.value = currentVehicle.label;

  return <TextField {...props} label="Vehicle" />;
}

Here's a working demo

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