dynamically change Mui Autocomplete value selection

Viewed 321

I am using Mui AutoComplete as select option for creating Formik Form.

<Autocomplete
  disablePortal
  options={vendors}
  getOptionLabel={(option) => option.vendor_company}
  onChange={(e, value) => {setFieldValue("vendor_id", value.id); }}
  renderInput={(params) => (
      <TextField
      error={Boolean(touched.vendor_id && errors.vendor_id)}
      helperText={touched.vendor_id && errors.vendor_id}
      onBlur={handleBlur}
      //onChange={handleChange}
      fullWidth
      {...params}
      label={t('Vendor')}
      />
  )}
/>

Below JSON data is pulled from server and returned,

vendor_id : 1

For adding new data selection value, this works perfectly.

But how to change field value based on Edit mode? Means I am getting data from server and I need to show server data in AutoComplete value,

Thank you,

2 Answers

You can use a state and set him with the data from your sever and put the value you want to display on property value of your autocomplete.

Say me if I miss the trouble you have, I can edit again.

Make use of 'value' prop of AutoComplete component, and pass the value that you want to show in edit mode as object of option, here's is a small example

JSX

import { useState } from "react";
import { Autocomplete, TextField } from "@mui/material";

const options = [
  { label: "The Godfather", id: 1 },
  { label: "Pulp Fiction", id: 2 },
];
const App = ({ editMode = true }) => {
  const [fieldValue, setFieldValue] = useState(editMode ? options[1] : null);
  return (
    <div className="App">
      <Autocomplete
        disablePortal
        options={options}
        onChange={(e, value) => {
          console.log(value);
          setFieldValue(value);
        }}
        value={fieldValue}
        renderInput={(params) => (
          <TextField
            onChange={(e) => setFieldValue(e.target.value)}
            label="Hello"
            {...params}
          />
        )}
      />
    </div>
  );
};
export default App;
Related