Skip to content
country-kit

Examples

React and Vue. Each section has a live preview and the code next to it.

Country select

Independent countries for a select. Store the alpha-2 code; display commonName.

getCountrySelectOptions ยท getCountry

Preview

Store
FR
ISO name
France
TLD
.fr
Currency
EUR
import { useMemo, useState } from 'react';
import { getCountry, getCountrySelectOptions } from 'country-kit';

export function ResidenceSelect() {
  const options = useMemo(
    () => getCountrySelectOptions({ independent: true }),
    [],
  );
  const [code, setCode] = useState('FR');
  const country = getCountry(code);

  return (
    <select value={code} onChange={(e) => setCode(e.target.value)}>
      {options.map((o) => (
        <option key={o.value} value={o.value}>{o.label}</option>
      ))}
    </select>
  );
  // persist country.code โ€” not the label
}

Phone prefix

Show dialCode in the picker (+1264 for Anguilla). callingCode is the E.164 country code (+1 for NANP).

searchCountries ยท getDialCode ยท getCallingCode

Preview

+1264

Display
+12644971234
E.164 country
+1
NANP
264
import { getCallingCode, getDialCode, searchCountries } from 'country-kit';

const [match] = searchCountries('Anguilla', { limit: 1 });
getDialCode(match.code);    // '+1264'  show in the picker
getCallingCode(match.code); // '+1'     ITU-T E.164 country code

Flags

getFlagSvgUrl returns a CDN URL (core package). Import country-kit/flags only for inline SVG markup.

getFlagSvgUrl ยท getCountryFlag ยท getCountry

Preview

Japan ๐Ÿ‡ฏ๐Ÿ‡ต

https://cdn.jsdelivr.net/gh/lipis/flag-icons@7.5.0/flags/4x3/jp.svg

import { getCountryFlag, getFlagSvgUrl } from 'country-kit';

<img src={getFlagSvgUrl('JP')} alt="Japan" />
<img src={getFlagSvgUrl('JP', { ratio: '1x1' })} alt="" />
getCountryFlag('JP'); // '๐Ÿ‡ฏ๐Ÿ‡ต'

TLD lookup

getCountryByTld maps IANA ccTLDs to alpha-2. gov.uk is GB, not .gb. .com is not a country TLD.

getCountryByTld

Preview

United Kingdom

.uk โ†’ GB

import { getCountryByTld } from 'country-kit';

function countryFromHost(value: string) {
  const host = value.includes('@')
    ? value.split('@').pop()!
    : value.replace(/^https?:\/\//, '').split(/[/?#]/)[0];
  return getCountryByTld('.' + host.split('.').pop());
}

countryFromHost('https://www.gov.uk'); // GB
countryFromHost('https://npmjs.com');  // undefined

Validation

isValidCountryCode is a type guard for assigned alpha-2 codes. getCountry also accepts alpha-3 and numeric. XK is not assigned.

isValidCountryCode ยท getCountry ยท isValidCallingCode

Preview

{
  "isValidCountryCode": false,
  "resolved": {
    "code": "US",
    "commonName": "United States"
  },
  "isValidCallingCode": false
}
import { getCountry, isValidCountryCode, type CountryCode } from 'country-kit';

function parseCountry(raw: string): CountryCode | undefined {
  if (isValidCountryCode(raw)) return raw;
  return getCountry(raw)?.code; // 'USA' / '840' โ†’ 'US'
}

parseCountry('XK'); // undefined (not ISO assigned)