garganurag893 / react-native-phone-number-input

React Native component for phone number.
MIT License
377 stars 219 forks source link

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

Open zaura-payments opened 2 years ago

zaura-payments commented 2 years ago

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!

kornatzky commented 2 years ago

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

mariomurrent-softwaresolutions commented 2 years ago

defaultCode?: CountryCode

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

baronchng commented 2 years ago

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}
  ...
/>
Irfanwani commented 1 year ago

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

mariomurrent-softwaresolutions commented 1 year ago

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

But this would reduce the flexibility

codekennML commented 3 months ago

If @baronchng solution does not work for you and you need to update the countryCode, via a prop from a previous screen , set the ref values using a useLayoutEffect

//These lines

phoneInput.current?.setState({ countryCode: countryCode, code: code.toString(), number: nationalNumber, });