Formik: Field type="checkbox", recommended way?

Created on 26 Apr 2018  路  7Comments  路  Source: formium/formik

Bug, Feature, or Question?

Question

the question

when using a <Field component="input" type="checkbox"> component to represent a checkbox, it seems i have to manually maintain the checked attribute, like this:

<Field name="f1" component="input" type="checkbox" checked={props.values.f1} />

is this the recommended approach?
i am just unsure, because the value attribute is maintained automatically, unlike checked.

Most helpful comment

Depends on your use case, of course...
This is my approach https://codesandbox.io/s/328038x19q

All 7 comments

Depends on your use case, of course...
This is my approach https://codesandbox.io/s/328038x19q

What about using a FieldArray for this purpose?

Can anyone give a simpler answer to the original question?

@Andreyco 's example is more complex: it supports an array of checkboxes.

I believed it is maintained automatically like value. I tried with a simple use case like @Andreyco and it works; here - https://codesandbox.io/s/sleepy-shannon-lpe81.

It is (mostly) maintained automatically. You still have to manage the checked state from the initial values. Here is a fork of @ameenaliu code sandbox: https://codesandbox.io/s/ecstatic-monad-58kjq

I couldn't believe that the checkbox would be so hard working with Formik.

Anyway, I found a very simple way to work with it.

_This is the MUI checkbox but I think with will work for native input checkbox as well._

                    <Checkbox
                      name="autoLogin"
                      value="true"
                      checked={autoLogin}
                    />

The autoLogin is a boolean variable.
The value surprisingly should be hardcoded as a string "true".

Hello, I leave you an example of Checkbox with SUIR, greetings!

<Field name='external' label='Client is External?' component={Checkbox} checked={values.external} onChange={() => setFieldValue('external', !values.external)} />

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jaredpalmer picture jaredpalmer  路  3Comments

outaTiME picture outaTiME  路  3Comments

jaredpalmer picture jaredpalmer  路  3Comments

jordantrainor picture jordantrainor  路  3Comments

Jungwoo-An picture Jungwoo-An  路  3Comments