javascriptreactjscookiesisojs-cookie

Get phone number prefix from Cookies in React


I know that we can get the iso code of a country with this method:

import Cookies from 'js-cookie';
const iso = Cookies.get('CK_ISO_CODE');
console.log(iso); // -> 'us'

Is there a way to get the phone prefix?

For example, for US it should be +1, for FR +33 and so on.


Solution

  • You'll want to use this npm package: https://www.npmjs.com/package/world-countries

    First here's an example that works in a snippet. We have to fetch the JSON file, so that eventListener is asynchronous, but if you use the npm package (next example) it won't have to be async.

    document.querySelector("#load-prefix").addEventListener("click", async () => {
      const world = await fetch(`https://cdn.jsdelivr.net/npm/world-countries@4.0.0/countries.json`).then(res => res.json())
      const iso = document.querySelector("#iso").value;
      const country = world.find(({cca2}) => cca2.toLowerCase() === iso.toLowerCase());
      const phonePrefixStart = country ? country.idd.root : "unknown";
      const phonePrefixEnd = country ? (country.idd.suffixes.length === 1 ? country.idd.suffixes[0] : "") : "";
      const phonePrefix = phonePrefixStart + phonePrefixEnd;
      document.querySelector("#output").innerText = phonePrefix;
    });
    <input placeholder="iso code" id="iso" />
    <button id="load-prefix">Get Phone Prefix</button>
    <p id="output"></p>

    With the npm package, it would look like this. (This example doesn't work because Stack Snippets doesn't include a module bundler)

    const world = require('world-countries')
    // or
    import world from "world-countries";
    
    document.querySelector("#load-prefix").addEventListener("click", () => {
      const iso = document.querySelector("#iso").value;
      const country = world.find(({cca2}) => cca2.toLowerCase() === iso.toLowerCase());
      const phonePrefixStart = country ? country.idd.root : "unknown";
      const phonePrefixEnd = country ? (country.idd.suffixes.length === 1 ? country.idd.suffixes[0] : "") : "";
      const phonePrefix = phonePrefixStart + phonePrefixEnd;
      document.querySelector("#output").innerText = phonePrefix;
    });
    <input placeholder="iso code" id="iso" />
    <button id="load-prefix">Get Phone Prefix</button>
    <p id="output"></p>

    So back to your question, it would look something like this:

    import Cookies from 'js-cookie';
    import world from "world-countries";
    const iso = Cookies.get('CK_ISO_CODE');
    console.log(iso); // -> 'us'
    const country = world.find(({cca2}) => cca2.toLowerCase() === iso.toLowerCase());
    const phonePrefixStart = country ? country.idd.root : "unknown";
    const phonePrefixEnd = country ? (country.idd.suffixes.length === 1 ? country.idd.suffixes[0] : "") : "";
    const phonePrefix = phonePrefixStart + phonePrefixEnd;
    console.log(phonePrefix); // -> '+1'