jorisre / react-telephone

☎️ Tiniest react phone input component (auto formating included)
https://react-telephone.joris.re/
MIT License
44 stars 6 forks source link

React hook form works with ...register but not with the Controller syntax #517

Closed vandercloak closed 1 year ago

vandercloak commented 1 year ago

I am trying to get the input to work with the hook form controller component and it throws an error when the defaultCountry value is set.

image
      <Controller
        control={control}
        name="phoneNumber"
        rules={{
          required: 'Please add a phone number',
        }}
        render={({ field, fieldState }) => (
          <Phone {...field} defaultCountry="us">
            <Phone.Country
              className={
                'rounded-br-none rounded-bl-none  focus:border focus:border-gray-300 focus:ring-transparent'
              }
            />
            <Phone.Number
              className={
                'rounded-tr-none rounded-tl-none border-t-0  focus:border focus:border-t-0 focus:border-gray-300 focus:ring-transparent'
              }
            />
          </Phone>
        )}
      />

Here is a sandbox of the issue https://stackblitz.com/edit/github-nhjwbd?file=src/components/samples/ReactHookForm.tsx

Any suggestions or ideas why this may be happening?

jorisre commented 1 year ago

You have to use the register method, not the Controller.

vandercloak commented 1 year ago

Gotcha, any insight into why it would break with Controller? I have it working with register, but I am hoping to get it working with the controller if I can

vandercloak commented 1 year ago

@jorisre is there a way to get it to work with default values?

 const { register, watch } = useForm<{ phoneNumber: string }>({
    defaultValues: {
      phoneNumber: '+12232323332',
    },
  });

https://stackblitz.com/edit/github-jngyyr?file=src/components/samples/ReactHookForm.tsx

jorisre commented 1 year ago

Currently, react-telephone work only in uncontrolled mode, I've to implement the controlled mode value to get it works with RHF Controller.

RHF Controller is meant to be used for controlled input but should use register when you can. And you can use it with react-telephone.

Note: It seems to have a bug with the default value, thank for reporting it, PR open if you want to contribute

jorisre commented 1 year ago

As a workaround, you can the defaultValue on the component:

<Phone {...register('phoneNumber')} defaultValue="+XXXXXXXXX">
vandercloak commented 1 year ago

Sounds good. Thank you for the quick replies! Yeah, link that issue and if I have time I will take a look