Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 e.g. "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 e.g. getting some info from the browser which can get me the country name? Please guide.

like image 259
Muhammad Sufyan Ramzan Avatar asked Jan 30 '19 08:01

Muhammad Sufyan Ramzan


People also ask

How do I find the country code of an IP?

You can use https://ip-api.io for this task easily.

How do you get geo location in react JS?

You can access a user's geolocation using the JavaScript API navigator. geolocation , which allows you to ask for location permission. If the user gives permission, location properties can be accessed. The first step is finding out if a user's geolocation is available or not.


2 Answers

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>
    )
}
like image 136
nadunc Avatar answered Sep 18 '22 11:09

nadunc


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);
  });
},[])
like image 27
Jyoti Duhan Avatar answered Sep 16 '22 11:09

Jyoti Duhan