danott / react-rails-form-helpers

Components for composing forms targeted at Rails
MIT License
81 stars 18 forks source link

CheckBox broken for true/false booleans #5

Closed ericdfields closed 7 years ago

ericdfields commented 7 years ago

I'm sending down data from a rails backend using active model serializers to form the json. Booleans come down as simply true or false, but checkboxes in rails want to work with 1/0. I'm not sure whether your lib is the problem, or if it's me.

If i use CheckBox like so:

import { CheckBox } from 'react-rails-form-helpers

class MyComponent extends Component {
  // handle mapping props to state
  // is_cohort will be true or false
  render() {
    <CheckBox name="is_cohort" defaultChecked={this.state.is_cohort} />
  }
}

It produces:

<span>
<input type="hidden" readonly="" value="0">
<input type="checkbox" name="my_model[is_cohort]" value="0">
</span>

What rails wants is:

<span>
<input type="hidden" name="my_model[is_cohort]" value="0">
<input type="checkbox" name="my_model[is_cohort]" value="1">
</span>

I've pulled this off rather inelegantly for now, complete with react yelling at my in dev mode by creating my own Checkbox component, like so:

const CheckBoxTag = ({ uncheckedValue = 0, ...props }) => {
  const propsWithDefault = { defaultValue: 0, ...props }

  return (
    <span>
      <HiddenFieldTag value={uncheckedValue} name={props.name} />
      <input type="checkbox" {...propsWithDefault} />
    </span>
  )
}

import { nameWithContext } from "react-rails-form-helpers/lib/utils"

export const CheckBox = nameWithContext(CheckBoxTag)

This works for me for now. Is there a bug in the lib, or am I just handling my booleans wrong?

danott commented 7 years ago

This is totally a bug!

-  const propsWithDefault = { defaultValue: 0, ...props }
+  const propsWithDefault = { defaultValue: 1, ...props }

Now I'm wondering if we should even use defaultValue, or should we rather use a specifically named prop of checkedValue to complement uncheckedValue 🤔

ericdfields commented 7 years ago

Something like that sounds right. And the name needs to get passed into the HiddenFieldTag.

On Jan 25, 2017, at 13:20, Dan Ott notifications@github.com wrote:

This is totally a bug!

  • const propsWithDefault = { defaultValue: 0, ...props }
  • const propsWithDefault = { defaultValue: 1, ...props } Now I'm wondering if we should even use defaultValue, or should we rather use a specifically named prop of checkedValue to complement uncheckedValue 🤔

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub, or mute the thread.

danott commented 7 years ago

This has been fixed in https://github.com/danott/react-rails-form-helpers/commit/4e409cc85470f28af2d731d7d63c24feae1de047, and released as beta.12.