Simplified Global Phone Number Input with React

Getting Started with React and react-phone-number-input

When building a form that accepts phone numbers from users worldwide, it’s essential to consider the complexities of international calling codes and formatting. In this tutorial, we’ll explore how to create a user-friendly phone number input field using React and the react-phone-number-input package.

Setting Up the Project

To begin, let’s create a new React project and install the required packages:

npm install react-phone-number-input styled-components

We’ll also obtain a free API key from Google to utilize the Google Maps API later in the project.

Designing the Form

Next, we’ll define a basic form with an input field, a select button, and labels. We’ll use styled-components to create two components, StyledPage for the container and StyledForm for the form, and add styles to both components.


import styled from 'tyled-components';

const StyledPage = styled.div`
  /* Add styles here */
`;

const StyledForm = styled.form`
  /* Add styles here */
`;

Adding Custom Form Inputs

We’ll utilize two custom inputs from the react-phone-number-input package: Input for the phone number and CountrySelect, a custom select element that we’ll define using two functions from the package, getCountries and getCountryCallingCode.


import { Input, getCountries, getCountryCallingCode } from 'eact-phone-number-input';

const CountrySelect = () => {
  const countries = getCountries();
  const countryOptions = countries.map((country) => (
      {country.name}
    
  ));

  return (
  );
};

We’ll also import a locale file that converts callingCodes to country names in English.

Detecting the User’s Location

To automatically detect the user’s location, we’ll use the browser’s Navigator API and the Google Maps Geocoding API. We’ll create a new function called lookupCountry.js to handle the data fetching and processing, returning a country code to our original callback function.


const lookupCountry = async () => {
  if ('geolocation' in navigator) {
    navigator.geolocation.getCurrentPosition(async (position) => {
      const response = await fetch(`https://example.com/geocode?latlng=${position.coords.latitude},${position.coords.longitude}`);
      const countryData = await response.json();
      return countryData.countryCode;
    });
  }
};

Connecting the Form Inputs

Finally, we’ll connect the state to the component, passing the values to the elements as props. We’ll use the country prop to control the formatting and masking of the phone number provided via a country calling code.


const PhoneNumberInput = () => {
  const [country, setCountry] = useState('');
  const [phoneNumber, setPhoneNumber] = useState('');

  const handleCountryChange = (countryCode) => {
    setCountry(countryCode);
  };

  const handlePhoneNumberChange = (phoneNumber) => {
    setPhoneNumber(phoneNumber);
  };

  return (
    
      
      
    
  );
};

Putting it All Together

When the user loads the page, they’ll be prompted to grant permission for the app to access their location. If they grant permission, the app will detect their location, look up the correct country code, and apply it to the form inputs on display.

Simplifying Global Phone Number Input

The react-phone-number-input package greatly simplifies the process of collecting global phone numbers in your form. By following this tutorial, you’ll learn how to create a user-friendly phone number input field that adapts to different countries and calling codes.

  • Easy integration: react-phone-number-input provides a simple way to add phone number input fields to your React application.
  • Automatic country detection: Using the browser’s Navigator API and the Google Maps Geocoding API, you can automatically detect the user’s location and apply the correct country code.
  • Customizable formatting: The package allows you to customize the formatting and masking of phone numbers based on the country calling code.

Leave a Reply