How to use material UI Checkbox with formik?

Viewed 3903

I am not able to code in the right way such that formik.values will reflect into Material UI's Checkbox

2 Answers

Checkboxes are a little tricky to include in third party forms packages, and Material UI doesn't help with that either.

What you need to do is use the FormControlLabel component to handle the onChangge event that formik needs. Then on the Checkbox you just set the checked prop to be whatever formik has in its values.

Here is an example I use for a Checkbox to set an isAdmin value.

const formik = useFormik({
  initialValues:{
     isAdmin: false
  },
});


<FormControlLabel
  control={<Checkbox checked={formik.values.isAdmin} />}
  label="is Admin"
  name="isAdmin"
  onChange={formik.handleChange}
/>

Using 'as'

Use the as prop with Formik Field and pass any props required to the Field itself. It will pass them onto FormControlLabel. For example, here the label field is passed down to FormControlLabel:

    <Formik>
        <Form>
        <Field
              as={FormControlLabel}
              type="checkbox"
              name="myFormikName"
              control={<Checkbox />}
              label="Text on screen"
            />
        </Form>
    </Formik>

Multiple checkboxes using 'as'

If you have multiple checkboxes with the same name (array) you need to pass the "checked" value like so. Checks if the Formik 'name' array includes the name.

const { values } = useFormikContext()

render (

    {names?.map(name => (
        <Field
        type="checkbox"
        name="names"
        value={name.fullName}
        key={name.id}
        as={FormControlLabel}
        control={
            <Checkbox
                checked={values.names.includes(name.fullName)}
            />
        }
        label={name.fullName}
        />
        ))}
)

Using 'setFieldValue'

    const { values, setFieldValue } = useFormikContext()

    <FormControlLabel
        label="This checks a box"
        control={
            <Checkbox
            checked={values.myCheckboxName}
            onChange={() =>
                setFieldValue(
                'myCheckboxName',
                !values.myCheckboxName,
                )
            }
            />
        }
    />
Related