How to Add a Country Code Picker with Phone Input in React Native

By Rashid •  Updated on: January 9th, 2023 • 

Phone number authentication is widely used in mobile apps. Country code picker and OTP are important components of Phone number authentication. In this blog post, let’s see how to create a country code picker with phone number input easily in react native.

The easiest way to create a country code picker is to use any third-party library. The react native phone number input library fits our purpose.

You can install the library into your react native project using any of the following commands.

npm i react-native-phone-number-input --save

or

yarn add react-native-phone-number-input

Following is the basic example of react native phone number input.

import React, {useState, useRef} from 'react';
import {View, Text, Alert, StyleSheet, Pressable} from 'react-native';
import PhoneInput from 'react-native-phone-number-input';

const App = () => {
  const [phoneNumber, setphoneNumber] = useState('');
  const phoneInput = useRef(null);
  const buttonPress = () => {
    Alert.alert(phoneNumber);
  };
  return (
    <View style={styles.container}>
      <PhoneInput
        ref={phoneInput}
        defaultValue={phoneNumber}
        defaultCode="IN"
        layout="first"
        withShadow
        autoFocus
        containerStyle={styles.phoneContainer}
        textContainerStyle={styles.textInput}
        onChangeFormattedText={text => {
          setphoneNumber(text);
        }}
      />
      <Pressable style={styles.button} onPress={() => buttonPress()}>
        <Text style={styles.continueText}>Get Phone Number</Text>
      </Pressable>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  phoneContainer: {
    width: '75%',
    height: 50,
  },
  button: {
    marginTop: 30,
    width: '75%',
    padding: 10,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'green',
  },
  textInput: {
    paddingVertical: 0,
  },
});

export default App;

In the above example, when the button is pressed the typed phone number is shown as an Alert. See the output given below.

react native phone number input

I hope this react native tutorial helps you to create a country code picker easily.

Rashid

Keep Reading