How to make a Toggle that work with react-hook-form?

Viewed 15

I'm using React Hook Form for my forms, but I'm struggling on how to implement a simple toggle.

I've tried a custom toggle: https://codesandbox.io/s/switch-component-with-tailwind-react-sbyxg?from-embed=&file=/src/App.js:168-244

or

react-toggle

but I can't find how to "bind" them to my form? The form doesn't get updated with those data.

 <Toggle icons={false} {...register('field-name')} />

--> doesn't reflect the initial value and doesn't update it.

<Controller
        control={control}
        name="field-name"
        render={({ field: { ref, ...field } }) => <Toggle icons={false} {...field} />}
      />

--> Gives a big error:

No overload matches this call.
  Overload 1 of 2, '(props: ToggleProps | Readonly<ToggleProps>): Toggle', gave the following error.
    Type '{ onChange: (...event: any[]) => void; onBlur: Noop; value: boolean; name: "isWorkingMonday"; icons: false; }' is not assignable to type 'Readonly<ToggleProps>'.
      Types of property 'value' are incompatible.
        Type 'boolean' is not assignable to type 'string | number | readonly string[] | undefined'.
  Overload 2 of 2, '(props: ToggleProps, context: any): Toggle', gave the following error.
    Type '{ onChange: (...event: any[]) => void; onBlur: Noop; value: boolean; name: "isWorkingMonday"; icons: false; }' is not assignable to type 'Readonly<ToggleProps>'.
      Types of property 'value' are incompatible.
        Type 'boolean' is not assignable to type 'string | number | readonly string[] | undefined'

SO yeah, not sure how to combine a react toggle and react-hook-form?

1 Answers

Well, just found the answer:

  <Controller
    control={control}
    name="field-name"
    render={({ field: {value, onChange } }) => <Toggle icons={false} checked={value} onChange={onChange} />}
  />
Related