reactjsredux-formreact-redux-formreact-toggle

How to use react-toggle with React redux-form?


Is it possible to use react-toggle with Redux form?

react-toggle renders a toggle like so:

<Toggle
  icons={false}
  onChange={this.handleToggleChange}
/>

Given a redux-form Field component like so:

              <Field
                name="email_newsletter"
                id="email_newsletter"
                component="input"
                type="checkbox"
              />

How can react-toggle update the value for the redux-form Field?

enter image description here


Solution

  • You can define a custom renderer like this:

    export const renderToggleInput = (field) => (
      <Toggle checked={field.input.value} onChange={field.input.onChange} icons={false} />
    );
    

    and set it to the component prop of the Field component:

    <Field
        name="email_newsletter"
        id="email_newsletter"
        component={renderToggleInput}
    />
    

    Warning: according to the value prop documentation, the value type need to be defined.

    It will be a boolean for checkboxes, and a string for all other input types. If there is no value in the Redux state for this field, it will default to ''. This is to ensure that the input is controlled. If you require that the value be of another type (e.g. Date or Number), you must provide initialValues to your form with the desired type of this field.

    So you need to define also initial value for your checkbox in your redux-form.

    You will find more details in the Redux-Form Field documentation