final-form / react-final-form

🏁 High performance subscription-based form state management for React
https://final-form.org/react
MIT License
7.39k stars 481 forks source link

Array values for third party checkbox component #252

Open A11oW opened 6 years ago

A11oW commented 6 years ago

Are you submitting a bug report or a feature request?

I think this is bug

What is the current behavior?

If create adapter component for Field with type="checkbox" and set value attribute. When checking the box will set the value to true, and unchecking the checkbox will set value to false.

What is the expected behavior?

Checking the box will add the value to the array, and unchecking the checkbox will remove the value from the array.

Sandbox Link

https://codesandbox.io/s/mmjkqqwy0y

What's your environment?

react-final-form 3.4.0 react 16.3.2

Other information

madspark commented 6 years ago

I think this feature would essentially work if the FieldProps "value" prop was made to work not only for checkboxes and ratio buttons: https://github.com/final-form/react-final-form#value-any .

crobinson42 commented 6 years ago

To achieve the true false expected behavior here @madspark is correct:

Checkboxes:

  • value is specified: the checkbox will be checked if the value given in value is contained in the array that is the value for the field for the form. Checking the box will add the value to the array, and unchecking the checkbox will remove the value from the array.
  • no value is specified: the checkbox will be checked if the value is truthy. Checking the box will set the value to true, and unchecking the checkbox will set the value to false.
joewestcott commented 5 years ago

This is my workaround for now. I'm passing input.onChange() an object that closely resembles an event.

<Field
  name="someArray"
  type="checkbox"
  value="someValue"
  component={({ input }) => (
    <div onClick={() => input.onChange({
      target: {
        type: "checkbox",
        checked: !input.checked
      }
    })}>
      {"The value is" + input.checked}
    </div>
  )}
/>

It would be nice if input.onChange() took a boolean directly. However this solution is still shorter than operating on the array myself, but it feels a bit hacky!