Pages - Menu

Redux Form - How to Set Checkbox Initial Value

Scope

We have a very simple requirement that wants to conditionally default the checkbox to checked for our checkout page.


Troubleshooting

Since we use react/redux, so naturally we use redux-form (currently at v6.8.0) for our form fields.

For a checkbox, our code will be like this.

<Field name={this.props.fields.addToAddressBook}
 id={this.props.fields.addToAddressBook}
 component="input"
 type="checkbox"
 checked={this.props.isAddToAddressBook}
 value={this.props.isAddToAddressBook}
 onChange={(e) => this.handleIsAddToAddressBook(e)}
/>

My state has the isAddToAddressBook: true.



However, in my console, the value is null even when the checkbox is checked.


Arguably we can use the checked field instead of the value, but Demandware doesn't allow that, so let's fix the value.

Tried a few different ways and still getting empty value.

value={this.props.isAddToAddressBook.toString()}

value={this.props.isAddToAddressBook ? 'true' : 'false'}

I also tried using defaultValue,

defaultValue={this.props.isAddToAddressBook}

it sets the defaultValue but not the value.


Solution

<input className="form-indent label-inline"
 name={this.props.fields.addToAddressBook}
 id={this.props.fields.addToAddressBook}
 type="checkbox"
 checked={this.props.isAddToAddressBook}
 value={this.props.isAddToAddressBook}
 onChange={(e) => this.handleIsAddToAddressBook(e)}
/>

Surprisingly and ironically, the solution is not to use redux-form field but normal redux binding.

Not an elegant solution if you need to write your own validation handler, but if validation is not required, this is actually cleaner. If it doesn't need to be in redux-form; then it shouldn't be in redux-form.

Reference

  • https://github.com/erikras/redux-form/issues/334
  • https://stackoverflow.com/questions/41452053/in-redux-form-how-can-i-set-the-initial-value-of-the-checked-property-of-a-chec

No comments:

Post a comment