Is there a way to get country phone prefix with react-native-localize? I can get country code, language code and may others things but I can't seem to get the phone prefix!
For example, in Spain prefix is 34, in US I think its 1
CodePudding user response:
You can use catamphetamine/libphonenumber-js for it. For example:
import getCountryCallingCode from 'libphonenumber-js'
getCountryCallingCode('RU') // returns '7'
getCountryCallingCode('IL') // returns '972'
CodePudding user response:
You could use an npm library such as country-telephone-data
Here is an example of how to do it with expo-localization
... but the principle would be very similar with react-native-localize
import {allCountries} from 'country-telephone-data';
import * as Localization from 'expo-localization';
import React, {useEffect, useState} from 'react';
import {Text} from 'react-native';
export const CountryDialCode = () => {
const [dialCode, setDialCode] = useState<string>();
// This sets a state variable for dial code with an async call that looks up the localisation region and then uses that to look up the country dial code.
useEffect(() => {
const getCountryTelephoneCode = async () => {
const {region} = await Localization.getLocalizationAsync();
if (!region) return;
const country = allCountries.find((country) => country.iso2 === region.toLowerCase());
console.log(country);
const _dialCode = country?.dialCode;
setDialCode(_dialCode);
};
getCountryTelephoneCode();
}, []);
return <Text>{dialCode}</Text>;
};