5 min read

Auto-SETTING Location in react-phone-input-2

Programming Tutorials

Aut-setting location in react-phone-input-2

SHARE THIS:

InstagramLinkedinImage

Introduction

While working on a WordPress subscription plugin, I faced a challenge that many developers encountered: enhancing user experience by auto-detecting and setting the user’s country in a phone input field. In this blog post, I’ll guide you through how I achieved this with the seamless integration of the react-phone-input-2 library with the extreme-ip-lookupAPI to achieve this functionality.

Setting up react-phone-input-2

First, you need to install the react-phone-input-2library:

npm install react-phone-input-2

This library allows you to embed a beautiful and intuitive phone input field in your React app.

Integrating with extreme-ip-lookup

The extreme-ip-lookupAPI offers IP-based geolocation lookup, which means it can return details about the location of a user based on their IP address. Among other details, it provides the country code, which we can use to set the default country in our phone input field.

To start using the extreme-ip-lookupAPI, sign up for an API key. For the purpose of this post, we’re using the demo key: demo2.

Implementing Auto Location Detection

Here’s the core code to implement this feature:

javascriptCopy code

import "./PhoneInputField.scss";

import "react-phone-input-2/lib/style.css";

import PhoneInput from "react-phone-input-2";

import LoadingSpinner from "./LoadingSpinner";

import React, { useState, useEffect } from "react";


const PhoneInputField = ({ onPhoneNumberChange }) => {

const [inputValue, setInputValue] = useState();

const [defaultCountry, setDefaultCountry] = useState("us");

const [loading, setLoading] = useState(true);


useEffect(() => {

setLoading(true);


fetch("https://extreme-ip-lookup.com/json/?key=demo2")

.then((response) => response.json())

.then((data) => {

if (data && data.countryCode) {

setDefaultCountry(data.countryCode.toLowerCase());

}

setLoading(false);

})

.catch((error) => {

setLoading(false);

console.error("Error fetching IP info:", error);

});

}, []);


const onChange = (value, country) => {

setInputValue(value);

onPhoneNumberChange(country.dialCode, value);

};


return (

<div className="csw-phone-input-container">

{loading ? (

<LoadingSpinner />

) : (

<div>

<label className="csw-label" htmlFor="phone">

Phone*

</label>

<div className="csw-input-wrapper">

<PhoneInput

id="phone"

country={defaultCountry}

inputProps={{

name: "phone",

required: true,

autoFocus: true,

}}

value={inputValue}

onChange={onChange}

inputClass="csw-input"

/>

</div>

</div>

)}

</div>

);

};


export default PhoneInputField;

Explaining the Code

  1. State Initialization: We set up states for the input value, the default country (preset to ‘us’), and a loading state.
  2. Fetching the Location: On component mount (useEffect), we fetch the user’s geolocation data from extreme-ip-lookup.Once the data is received, we update the defaultCountrystate with the country code provided by the API.
  3. Displaying the Input Field: If the data is still loading, a LoadingSpinnercomponent is displayed. Otherwise, the PhoneInputcomponent react-phone-input-2is shown with the detected country pre-selected.

Conclusion

By integrating react-phone-input-2with extreme-ip-lookup,we can significantly enhance the user experience by auto-detecting and pre-selecting the user’s country in the phone input field. This reduces friction and potential errors, providing a smoother journey for the user. Try it out in your next project and see the difference for yourself!