react-native-phone-number-input icon indicating copy to clipboard operation
react-native-phone-number-input copied to clipboard

Is there a way of setting the country code/dialing code?

Open zaura-payments opened this issue 3 years ago • 6 comments

Hello the package is very useful so far but I just need to know how to set the country code after the component has already rendered.

For example if I have the string "+44" what function would I need to call in order to update the country code that appears in the text input? Is there anyway of doing this?

Thanks!

zaura-payments avatar Jan 06 '22 14:01 zaura-payments

Seems you cannot set the defaultCode from a variable, like defaultCode={country}

kornatzky avatar Jan 09 '22 17:01 kornatzky

defaultCode?: CountryCode

You could map the +44 to a CountryCode item and then set the defaultCode

Obtain your country code, number without country code, code (number) using google-libphonenumber.

import PhoneInput from 'react-native-phone-number-input';
import { CountryCode } from 'react-native-country-picker-modal';
import { PhoneNumberUtil } from 'google-libphonenumber';

const phoneUtil = PhoneNumberUtil.getInstance();
const phoneInput = useRef<PhoneInput>(null);

const parsedNo = phoneUtil.parse('1234567890', '');
if (parsedNo.hasNationalNumber()) {
  const nationalNumber = parsedNo.getNationalNumberOrDefault().toString();
  const code = parsedNo.getCountryCodeOrDefault();
  const countryCode = phoneUtil.getRegionCodeForCountryCode(code) as CountryCode;

  // it's ugly, but it works
  phoneInput.current?.setState({
    countryCode: countryCode,
    code: code.toString(),
    number: nationalNumber,
  });
}

...

<PhoneInput
  ...
  ref={phoneInput}
  ...
/>

baronchng avatar Aug 06 '22 17:08 baronchng

is there any better way to do it. This should be a built-in feature in this package

Irfanwani avatar Dec 08 '22 04:12 Irfanwani

is there any better way to do it. This should be a built-in feature in this package

But this would reduce the flexibility