Home > Software engineering >  Detecting country code for react-native-phone-number
Detecting country code for react-native-phone-number

Time:11-06

I use the react-native-phone-number-input library. I want the country flag to be determined automatically depending on where I'm from. How do I implement this?

<PhoneInput
  ref={phoneInput}
  defaultValue={value}
  // defaultCode="DM"
  layout="first"
  // onChangeText={(v) => setValue(v)}
  onChangeFormattedText={(v) => setValue(v)}
  placeholder={' '}
  defaultCode="IN"
  withDarkTheme
  withShadow
  autoFocus
  containerStyle={{
    borderRadius: 0,
    width: '100%',
    height: 49,
  }}
  textInputStyle={{height: 68}}
  textContainerStyle={{paddingTop: 15}}
/>

CodePudding user response:

you can set default country based on IP , hit API Geolocation which return countrycode or something. then return to your apps

CodePudding user response:

The react-native-localize package can be used to get the country code of the current users device - and I assume this can just then be passed in to your PhoneNumber component to display the correct country flag.

import * as RNLocalize from "react-native-localize";

console.log(RNLocalize.getCountry());
// -> "FR"

I assume this would then work

<PhoneInput
  ref={phoneInput}
  defaultValue={value}
  // defaultCode="DM"
  layout="first"
  // onChangeText={(v) => setValue(v)}
  onChangeFormattedText={(v) => setValue(v)}
  placeholder={' '}
  defaultCode={RNLocalize.getCountry()}
  withDarkTheme
  withShadow
  autoFocus
  containerStyle={{
    borderRadius: 0,
    width: '100%',
    height: 49,
  }}
  textInputStyle={{height: 68}}
  textContainerStyle={{paddingTop: 15}}
/>
  • Related