React Native International Phone Number Input
Installation
$ npm i --save react-native-international-phone-number
OR
$ yarn add react-native-international-phone-number
AND
Update your metro.config.js
file:
module.exports = {
...
resolver: {
sourceExts: ['jsx', 'js', 'ts', 'tsx', 'cjs', 'json'],
},
};
Basic Usage
import React, { useState } from 'react';
import { View, Text } from 'react-native';
import {
phoneMask,
PhoneInput,
} from 'react-native-international-phone-number';
export default function App() {
const [selectedCountry, setSelectedCountry] = useState(undefined);
const [phoneInput, setPhoneInput] = useState('');
return (
<View style={{ width: '100%', flex: 1, padding: 24 }}>
<PhoneInput
selectedCountry={selectedCountry}
setSelectedCountry={setSelectedCountry}
value={phoneInput}
onChangeText={(newValue) =>
setPhoneInput(
phoneMask(newValue, selectedCountry.callingCode[0])
)
}
/>
<View style={{ marginTop: 10 }}>
<Text>
Country:{' '}
{`${selectedCountry?.name} (${selectedCountry?.cca2})`}
</Text>
<Text>
Phone: {`${selectedCountry?.callingCode[0]} ${phoneInput}`}
</Text>
</View>
</View>
);
}
Advanced Usage Using React-Hook-Form ans Typescript
import React, { useState } from 'react';
import { View, Text } from 'react-native';
import {
phoneMask,
PhoneInput,
} from 'react-native-international-phone-number';
import { Country } from 'react-native-country-picker-modal';
import { Controller, FieldValues, useForm } from 'react-hook-form';
interface FormProps extends FieldValues {
phoneNumber: string;
}
export default function App() {
const [selectedCountry, setSelectedCountry] = useState<
undefined | Country
>(undefined);
const { control, handleSubmit, resetField } = useForm();
function onSubmit(form: FormProps) {
Alert.alert(
'Advanced Result',
`${selectedCountry?.callingCode[0]} ${form.phoneNumber}`
);
resetField('phoneNumber');
}
return (
<View style={{ width: '100%', flex: 1, padding: 24 }}>
<Controller
name="phoneNumber"
control={control}
render={({ field: { onChange, value } }) => (
<PhoneInput
selectedCountry={selectedCountry}
setSelectedCountry={setSelectedCountry}
value={value}
onChangeText={(newValue) =>
onChange(
phoneMask(newValue, selectedCountry.callingCode[0])
)
}
/>
)}
/>
<Button
style={{
width: '100%',
marginTop: 10,
backgroundColor: '#90d7ff',
}}
onPress={handleSubmit(onSubmit)}
/>
<Text>Submit</Text>
</Button>
</View>
);
}
Props
value?
: stringonChangeText?
: (text: string) => voidcontainerStyle?
: StylePropinputStyle?
: StylePropwithDarkTheme?
: booleandisabled?
: booleanplaceholder?
: stringplaceholderTextColor?
: string
Methods
phoneMask
: (value: string, countryCode: string) => string
Contributing
- Fork or clone this repository
$ git clone https://github.com/AstrOOnauta/react-native-international-phone-number.git
Thanks for stopping by! 😁