Below code works for me and i want to know how its working. The code is actually getting the country code based on the ip address and loading it into the input box.
My doubts are:
loadJSONP() function loads the script but why they are mentioning callback string as query paramater.lookup() function how they are getting the value from the script url that was loaded previously and removedimport React from 'react';
import ReactDOM from 'react-dom';
import IntlTelInput from 'react-intl-tel-input';
import 'react-intl-tel-input/dist/main.css';
const loadJSONP = (url, callback) => {
const ref = window.document.getElementsByTagName('script')[0];
const script = window.document.createElement('script');
script.src = `${url + (url.indexOf('?') + 1 ? '&' : '?')}callback=${callback}`;
ref.parentNode.insertBefore(script, ref);
script.onload = () => {
script.remove();
};
};
const lookup = (callback) => {
loadJSONP('ipinfo.io', 'sendBack');
window.sendBack = (resp) => {
const countryCode = (resp && resp.country) ? resp.country : '';
callback(countryCode);
}
};
ReactDOM.render(
<IntlTelInput
defaultCountry="auto"
geoIpLookup={lookup}
css={['intl-tel-input', 'form-control']}
/>,
document.getElementById('root'),
);
Sivabalan
Coding
In short this piece of code makes a remote call to ipinfo.io to get that information from the IP
const lookup = (callback) => {
loadJSONP('ipinfo.io', 'sendBack');
window.sendBack = (resp) => {
const countryCode = (resp && resp.country) ? resp.country : '';
callback(countryCode);
}
};
As you always need to have a lookup table to relate IP to country.
Joe Clark
Full-stack developer specializing in healthcare IT
JSONP is used to get around the issue where an ajax call goes out to another domain. Ajax calls are usually on the same domain. Cross-domain calls are not permitted for security reasons, so when you know security isn't an issue, then that can be circumvented using JSONP with a callback.