Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declarative Formik forms with MUI

I would like to use formik with MUI. There doesn't seem to be a clear path to do this, the documentation does not make sense and the examples are nonsensical with compared to the docs.

For example. This page is at the top level of formik's examples. It is the only example that I can find on formik's site where MUI is integrated.

  • The example uses the hooks method. There doesn't seem to be an example of the component method
  • The example imports the button and the text field from the core material UI package. However, in this sandbox, components are imported from @mui/material and form formik-mui. Why two different package? Why isn't this covered in the docs?

All I want to do is build a formik form with mui styling and I can't find any docs for that.

For example, if I want to use a MUI text field, there are online examples that suggest using this method. However, once again I cannot find this in the docs and there is no explanation as to what is happening here or how I apply any props to this text field.

    <Form>
      <Field
        type="email"
        name="email"
        component={TextField}
        color={"error"}
      />

What am I missing here? I just want to build declarative formik forms with MUI.

like image 823
Joshua Foxworth Avatar asked Sep 17 '26 12:09

Joshua Foxworth


1 Answers

MuI and Formik are well documented, the only issue is the connection part is missing in both documentations.

For declarative formik you should switch from hook to render prop.

<Formik
    //
    initialValues={{ email: '' } as FormValues}
    onSubmit={handleOnSubmit}
>
    {(formik: FormikProps<FormValues>) => (
        <Form>
        </Form>
    )}
</Formik>

To clear a little bit your confusion with the connection part. Mui don't use Formik so you must code an all form fields the connection to formik yourself.

<TextField
    name="email"
    label="Email"
    value={formik.values.email}
    onChange={formik.handleChange}
    error={formik.touched.email && Boolean(formik.errors.email)}
    helperText={formik.touched.email && formik.errors.email}
/>

For those repetative work it exists these neat library formik-mui. If you use the library, it's just the following template left.

Attention: The TextField comes from formik-mui

import { TextField } from 'formik-mui';

<Field
    component={TextField}
    name="email"
    label="Email"
/>
like image 60
Maximus Avatar answered Sep 21 '26 23:09

Maximus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!