Home > Software engineering >  MUI Autocomplete change selected option when another field changes
MUI Autocomplete change selected option when another field changes

Time:03-08

I have two fields with MUI and Formik, a normal TextField and Autocomplete field. I need select an option on Autocomplete when TextField changes, how do this?

In formik it's all ok, the values sent correct data, but autocomplete do not change to correct value.

Example: https://codesandbox.io/s/compassionate-river-f32btt?file=/src/demo.js

CodePudding user response:

The options property is an array but the value is represented by a string. You need to pass a function to the isOptionEqualToValue property that the AutoComplete component will use to figure out which item in the array of items matches the current value.

You also need to move the value property out of the text field and pass it directly to the autocomplete so that it can manage its own value.

<Autocomplete
  filterSelectedOptions
  id="estado"
  name="estado"
  options={states}
  clearText="Apagar"

  // Add the following props
  isOptionEqualToValue={(option, value) => option.value === value}
  value={formik.values.estado}

  renderInput={(params) => (
    <TextField
      {...params}
      error={Boolean(formik.errors.estado)}
      helperText={formik.errors.estado}
    />
  )}
  onChange={(e, newValue) => {
    formik.handleChange({
      target: { name: "estado", value: newValue.value },
    });
  }}
/>;

CodePudding user response:

You can probably arrange this better, but this works

  const [selected, setSelected] = useState(null);
  
  function onBlurCep(ev, setFieldValue) {
    let selected = states.find((v) => v.label === formik.values.cep) || {};
    setSelected(selected);

  - - - -

  <Autocomplete
      value={selected}
  • Related