Search code examples
reactjsreact-final-formreact-final-form-arrays

How to format the value of a checkbox Field using React Final Form Field Array?


In React Final Form, we can use format or parse props for text type inputs in order to store a different value than the one specified, but this does not seems to work the same way with checkboxes.

Example:

<FieldArray name='test' initialValue={[true, false]}>
    <Field 
        component='input' 
        type='checkbox' 
        format={value => value ? 'foo' : null} 
        parse={value => value ? 'foo' : null}/>
    </Field>
</FieldArray>

in this example, the value to store will still be true or false, regardless the use of format and parse. Is it possible to format values from [true, false] to ["foo"]?

Thanks in advance for any help.


Solution

  • Your format function needs to convert it back into a boolean.

    <Field
      name="employed"
      component="input"
      type="checkbox"
      format={v => v === "foo"}
      parse={v => (v ? "foo" : null)}
    />
    

    But it sounds like you're wanting the already-built-in functionality of using checkboxes to manage membership in an array. To do that, you just specify a value prop to <Field/>. See the "Sauces" example:

    Edit quirky-voice-zruje

    ☝️ Also includes the format/parse example.