React Native Phone Number Input
React Native + Phone Input + International Number Verification
The motivation behind building this package is due to lack of any well-maintained React-Native package to add an international number with proper calling code and with correct validation.
In this article, we will use react-native-phone-number-input which allows users to add their country code and country flag before typing their personal phone numbers.
So, Let’s start by installing the package:
yarn add react-native-phone-number-input
OR
npm i react-native-phone-number-input --save
Import
import PhoneInput from "react-native-phone-number-input";
Usage
Declare state variables for extracting value.
import React, { useState, useRef } from "react";
import {
SafeAreaView,
StyleSheet,
View,
StatusBar,
TouchableOpacity,
Text,
} from "react-native";
import PhoneInput from "react-native-phone-number-input";const App: React.FC = () => {
const [value, setValue] = useState("");
const [valid, setValid] = useState(false);
const [showMessage, setShowMessage] = useState(false);
const phoneInput = useRef<PhoneInput>(null);
return (
<PhoneInput
ref={phoneInput}
defaultValue={value}
defaultCode="IN"
onChangeFormattedText={(text) => {
setValue(text);
}}
withDarkTheme
withShadow
autoFocus
/>
);
};
export default App;
To check if the number is correct or not, add a button and if the validation is successful then proceed further.
<TouchableOpacity
style={styles.button}
onPress={() => {
const checkValid = phoneInput.current?.isValidNumber();
setValid(checkValid ? checkValid : false);
//proceed
}}>
<Text>Check</Text>
</TouchableOpacity>
Conclusion
One of the major components while building any modern web and mobile application requires an authentication method, and phone number verification is one the most popular way to do that. I built this package to ensure phone number validation for most of the international numbers.
That’s it. I hope you enjoyed this read.