Search code examples
javascriptreactjsmaterial-uiformikformik-material-ui

Formik's forms don't recognize material UI component's text field value?


I built a simple contact page using formik and material UI. Everything works except for when I use the Material UI components instead of regular input tags. It seems like the program can't read the value inside the Material UI TextField component.

This works:

                     <Field 
                        name="name" 
                        id="outlined-textarea"
                            label="First Name"
                            variant="outlined"
                            margin="dense"
                            component='input'
                            />
                    <ErrorMessage name="name" className="errorMsg" component="p" />

This doesn't work:

                      <Field
                        name="lastName"
                        id="outlined-textarea"
                        label="Last Name"
                        component={TextField}
                        variant="outlined"
                        margin="dense"
                    />
         <ErrorMessage name="lastName" className="errorMsg" component="p" />

I created a sandbox of the code here.


Solution

  • To hook formik properly with material ui, use render prop (instead of component) and grab the formik field which you get and pass it down to material ui Textfield

    Like this

    <Field
        name="lastName"
        id="outlined-textarea"
        label="Last Name"
        render={({ field }) => <TextField {...field} />}
        variant="outlined"
        margin="dense"
      />