Home > database >  Default value of Autocomplete is undefined in MUI v5
Default value of Autocomplete is undefined in MUI v5

Time:11-06

I have set the defaultValue prop in Autocomplete component of MUI v5 but the value is always undefined.

Excerpt from my code

const cars = [
  { label: "BMW", code: "Volkswagen" },
  { label: "Benz", code: "Mercedes" }
];

...

 const formik = useFormik({
    initialValues: {
      car: ""
    },
    onSubmit: (values) => {}
  });

...
      <Autocomplete
        id="autocomplete"
        options={cars}
        getOptionLabel={(option) => `${option.code} - ${option.label}`}
        renderOption={(props, option) => (
          <Box component="li" {...props}>
            {option.code} - {option.label}
          </Box>
        )}
        defaultValue={`${cars[0].code} - ${cars[0].label}`}
        onChange={(e, value) => {
          formik.setFieldValue("car", `${value.code} - ${value.name}`);
        }}
        renderInput={(params) => (
          <TextField
            {...params}
            id="textField"
            name="cars"
            label="Cars"
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            inputProps={{
              ...params.inputProps,
              autoComplete: "new-password"
            }}
          />
        )}
      />

I created a working example using Edit autocomplete (forked)

CodePudding user response:

You got undefined-undefined because you have already described how the selected property should look like here:

getOptionLabel={(option) => `${option.code} - ${option.label}`}

Therefore, you should pass to default option an object where it's possible to access code and label values. Changing defaultValue={cars[0]} will help.

Working Demo

  • Related