My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Can anyone explain me how the below code works

Sivabalan's photo
Sivabalan
·Jan 31, 2019

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:

  1. loadJSONP() function loads the script but why they are mentioning callback string as query paramater.
  2. lookup() function how they are getting the value from the script url that was loaded previously and removed
import 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('http://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'),
);