formik icon indicating copy to clipboard operation
formik copied to clipboard

Field type="checkbox", recommended way?

Open gabor opened this issue 8 years ago • 7 comments

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.

gabor avatar Apr 26 '18 14:04 gabor

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

Andreyco avatar Apr 26 '18 20:04 Andreyco

What about using a FieldArray for this purpose?

c10b10 avatar Apr 05 '19 07:04 c10b10

Can anyone give a simpler answer to the original question?

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

huylift avatar Jun 18 '19 16:06 huylift

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.

ameenaliu avatar Sep 02 '19 16:09 ameenaliu

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

mikemclin avatar Sep 07 '19 14:09 mikemclin

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".

dennisat avatar Jan 15 '20 08:01 dennisat