6

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

halfer
  • 19,824
  • 17
  • 99
  • 186
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

1 Answers1

8

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

Adrien Lacroix
  • 3,502
  • 1
  • 20
  • 23
  • thank you.. that errors w `Warning: Failed prop type: Invalid prop `checked` of type `string` supplied to `Toggle`, expected `boolean`.` – AnApprentice Aug 12 '17 at 15:57
  • I tried changing it to `checked={field.input.value == 'true')} ` given the react-toggle returns a string not a boolean... now the toggle can be set from false to true, but not back from true to false, it gets stuck – AnApprentice Aug 12 '17 at 16:06
  • @AnApprentice I think I found your problem, I updated my answer – Adrien Lacroix Aug 12 '17 at 16:13
  • sorry, not seeing any change to the idea? – AnApprentice Aug 12 '17 at 16:14
  • @AnApprentice, you need to provide `initialValues` to your `redux-form` with `email_newsletter` set to `true` or `false` (just to ensure the boolean type) – Adrien Lacroix Aug 12 '17 at 16:16
  • `` is what's needed to add the checkbox per example https://redux-form.com/7.0.3/examples/simple/ thanks @AdrienLacroix – jackhowa Jan 09 '20 at 20:31