Home > OS >  Autocomplete MUI with Formik - Pass data to Formik
Autocomplete MUI with Formik - Pass data to Formik

Time:12-20

I'm using MUI Autocomplete component and I want to validate the content using formik. With a simple text input its easy, passing the formik.handleChange on the onChange event. Instead with autocomplete this is not working. Can someone help me?

Using onGenderChange function I am at least able to set the internal state of my component and console.log the selected value. Is it possible from here to use formik.handleChange to fire the validation I have ready in my parent component?

<TextField
    id="firstName"
    name="firstName"
    label="Nome"
    fullWidth
    autoComplete="off"
    variant="standard"
    value={formik.values.firstName}
    onChange={formik.handleChange}
    error={Boolean(formik.errors.firstName)}
    helperText={formik.touched.firstName && formik.errors.firstName}
/>

<Autocomplete
    name="gender"
    id="gender"
    disablePortal
    getOptionLabel={(option) => option || ""}
    options={["Maschio", "Femmina", "Altro"]}
    renderInput={(params) => <TextField {...params} variant="standard" label="Genere" fullWidth />}
    value={this.gender}
    onChange={this.onGenderChange}
    error={Boolean(formik.errors.gender)}
    helperText={formik.touched.gender && formik.errors.gender}
/>

onGenderChange = (event, value) => {
    this.setState({
        gender: value
    }, () => {
        console.log(this.state.gender);
    });
}

CodePudding user response:

it's not updating formik state because the Autocomplete onChange has a different structure, the event prop doesn't have a value in which the formik handleChange function needs. so to fix that there are two ways:

  1. construct a correct event for formik handleChange

onChange={(e, value) => {
 const event = {...e, target: { ...e.target, name: "gender", value: value }};
 formik.handleChange(event);
}}

2 - use formik setFieldValue

onChange={(e, value) => formik.setFieldValue("gender", value)}

  • Related