Search code examples
javascriptreactjsreduxredux-form

In Redux Form, how can I set the initial value of the checked property of a checkbox?


In our Redux Form 5.3 (not 6.x) app, I want to render an <input type="checkbox" /> like so:

// In some cases, fieldHelper.checked is initially undefined. Then, when the
// user clicks one of the checkboxes, fieldHelper.checked is
// explicitly set to true or false. This change from one of the component's
// props being undefined to having a value causes a React warning; see
// http://stackoverflow.com/a/38015169/473792 and
// https://facebook.github.io/react/docs/forms.html#controlled-components
// So to prevent that warning, we do a quick null check on
// fieldHelper.checked and replace it with false explicitly if it is
// undefined before rendering the checkbox.
const fieldHelper = this.props.field['checkbox'];
const checked = fieldHelper.checked || false;

const modifiedFieldHelper = Object.assign({}, fieldHelper);
delete modifiedFieldHelper.checked;

return (
  <input
    checked={checked}
    {...modifiedFieldHelper}
  />
);

}

As noted in the comment, in my testing environment, this.props.field['checkbox'].checked is undefined immediately after mounting the <input>. As a result, when my tests modify the value of this.props.field['checkbox'].checked, I get the following warning:

Warning: ApplicantForm is changing an uncontrolled input of type checkbox to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

... Unless I explicitly set the checked prop on the <input> to false instead of undefined, as demonstrated in the code snippet I posted above.

Instead of using this null check, I would like to set the initial value of this.props.fields['checkbox'].checked before my tests run. I know I can set the initial value of fields in Redux Form. Is there a way to set the initial value of an auxiliary property like the checked property that Redux Form also controls?


Solution

  • You could create a simple conditional in your checked attribute so that when the value is undefined you just return false:

    <input 
      type="checkbox" 
      checked={typeof this.props.fields['checkbox'].checked == 'undefined'?false:this.props.fields['checkbox'].checked} 
      onClick={() => {... your onClick code ...}} />