How To implement ReactFlagsSelect with React Hook Form Controller

Viewed 113

I tried to implement with React Hook From using <Controller />. While I am submitting the form country field return undefined.

<Controller 
  name="country"
  control={control}
  render={({ field: { onChange, value } }) => (
    <ReactFlagsSelect
      selected={selected}
      onSelect={code => handleChange(code)}
      value={value}
      onChange={onChange}
    />
  )}
/>
1 Answers

The problem is you pass RHF's onChange handler to the wrong prop. <ReactFlagsSelect /> doesn't have a onChange prop, instead you should pass it to the onSelect prop.

<Controller 
  name="country"
  control={control}
  render={({ field: { onChange, value } }) => (
    <ReactFlagsSelect
      selected={selected}
      onSelect={onChange}
      value={value}
    />
  )}
/>

Side-note: RHF's will update value changes to your registered fields in it's internal form state, so there is no need to use extra state management for these values via useState or something similar. If you really need to call your handleChange callback, you can do both in the onSelect callback.

<Controller 
  name="country"
  control={control}
  render={({ field: { onChange, value } }) => (
    <ReactFlagsSelect
      selected={selected}
      onSelect={code => {
        onChange(code);
        handleChange(code);
      }}
      value={value}
    />
  )}
/>
Related