Sougata Mukherjee
Sougata Mukherjee

Reputation: 603

how to set country code automatically by region wise in react?

in this phone number country code how is it possible to set automatically country code by region wise. like if I open the website in USA its shows country code +1 automatically, if I open the website in INDIA its shows country code +91 automatically.Like weather API is there any API that should check automatically country code

import React from "react";
import PhoneInput, {isValidPhoneNumber
} from "react-phone-number-input";
export default function App() {
  const [fields, setFields] = React.useState([{ value: null }]);

  function handleChange(i, event) {
    if (event) {
      const values = [...fields];
      values[i].value = event;
      setFields((v) => values); 
    }
  }

  return (
    <div className="App">
     
      {fields.map((field, idx) => (
        <PhoneInput
          key={idx}
          id="phoneNumbers1"
          type="text"
          placeholder="Enter phone number "
          value={field.value || ""}
          defaultCountry="IN"
          international
          name="phoneNumbers"
          autoComplete="off"
          onChange={(e) => handleChange(idx, e)}
          
        />
      ))}
      <button
        type="button" >
        Phone Number
      </button>
    </div>
  );
}

Upvotes: 1

Views: 4383

Answers (1)

Tyler Durden
Tyler Durden

Reputation: 1070

To detect the country, the React app needs to look up the IP address using IP-to-Location services like IPRegistry

Here is a client-side example with IPRegistry :

const getCountryBtn = document.getElementById("getCountry");
const countryNameElement = document.getElementById("country");
getCountryBtn.onclick = function() {
  fetch('https://api.ipregistry.co/?key=tryout')
    .then(function (response) {
        return response.json();
    })
    .then(function (payload) {
        countryNameElement.innerHTML = payload.location.country.name;
    });
}
<html>
<body>
  <button id="getCountry">Get Country</button>
  <div id="country"></div>
</body>
</html>

Once the country name is available, its corresponding country code can be set as the default value in the React component.

Upvotes: 3

Related Questions