简体   繁体   中英

Autocomplete Set Default Value in React

I need to have a default value in my autocomplete in my react app. My problem is when i try to submit it, it still is invalid. Meaning it has no value in it. I need to click the autocomplete and select it again just to make to have the value.

Pls check this codesandbox link CLICK HERE

          <Autocomplete
            name="member_status"
            value={values.member_status}
            options={memberStatuses ? memberStatuses : []}
            getOptionLabel={(memberStatus) => memberStatus.name}
            onChange={(e, value) => {
              setFieldValue(
                "member_status",
                value !== null ? value.id : ""
              );
            }}
            renderInput={(params) => (
              <TextField
                {...params}
                label="Member Status"
                name="member_status"
                variant="outlined"
                onBlur={handleBlur}
                helperText={
                  touched.member_status ? errors.member_status : ""
                }
                error={
                  touched.member_status && Boolean(errors.member_status)
                }
              />
            )}
          />

The issue here is you are setting the initial value of your Autocomplete as an object , then you're validating for a string .

Changing your validationSchema to

const validationSchema = yup.object().shape({
  member_status: yup
    .object()
    .shape({
      id: yup.number(),
      name: yup.string()
    })
    .nullable()
    .required("Select member status")
});

and your Autocomplete 's onChange handler to

...
onChange={(e, value) => {
  setFieldValue("member_status", value); // set the new value to an object, not string
}}

should work.

编辑 autocomplete-formik-material-ui-react(分叉)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM