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.
You can use https://ip-api.io for this task easily.
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.
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);
});
},[])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With