简体   繁体   中英

How to get country code and Country name using IP in react js

I am working on an application which is based on react.js. One of the requirements in the app is to detect the location(Country) from where it is opened and then pre-fill the phone number field on a form with the flag of this country.

I am thinking that it would be done more efficiently by first detecting the IP address and then finding out the country name using this IP address. For that purpose, I have tried many libraries eg "iplocation", "geoip-country-lite", "ip" etc but these are not compatible with my application. Can any please suggest me other library using which I can get the country name?

Or there is any other effective solution instead of detecting the IP address eg getting some info from the browser which can get me the country name? Please guide.

You can do this without using jQuery.

Install & import axios from npm

import axios from 'axios'

Initialize your component state with country name & country code

constructor(props) {
    super(props);
    this.state = {
        countryName: '',
        countryCode: ''
    }
}

Add this function to your component

getGeoInfo = () => {
    axios.get('https://ipapi.co/json/').then((response) => {
        let data = response.data;
        this.setState({
            countryName: data.country_name,
            countryCode: data.country_calling_code
        });
    }).catch((error) => {
        console.log(error);
    });
};

And call this.getGeoInfo() to set country name & country code to your state. I called that from componentDidMount()

componentDidMount(){
    this.getGeoInfo();
}

And you can read the state to get country name & country code

render() {
    return (
        <div>
            <p>Country Name: {this.state.countryName}</p>
            <p>Country Code: {this.state.countryCode}</p>
        </div>
    )
}

With React hooks, this can be done like below:

import React, { useEffect } from 'react';

 useEffect(() => {
   fetch('https://extreme-ip-lookup.com/json/')
   .then( res => res.json())
   .then(response => {
    console.log("Country is : ", response);
  })
  .catch((data, status) => {
    console.log('Request failed:', data);
  });
},[])

You can use an external API to get location details from the client IP address.

I've redone this to use http://api.hostip.info , which is free to use, and I'm using Fetch rather than jQuery to pull the data.

 function getElementText(response, elementName) { return response.getElementsByTagName(elementName)[0].innerHTML; } function getIpAddress() { fetch('http://api.hostip.info').then(response => { return response.text(); }).then(xml => { return (new window.DOMParser()).parseFromString(xml, "text/xml"); }).then(xmlDoc => { countryName = getElementText(xmlDoc , "countryName"); countryCode = getElementText(xmlDoc , "countryAbbrev"); $("#output").html("Country name: " + countryName + "<br>" + "Country code: " + countryCode); }); }
 <div style="text-align:center;line-height:30px;"> <button onclick="getIpAddress()">Click me to get IP AddressInfo </button> <div id="output">Location:</div> </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM