Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Autocomplete MUI with Formik – Pass data to Formik

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);
    });
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading