1.1.1 • Published 1 year ago

react-country-state-dropdown v1.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

react-country-state-dropdown

GitHub release GitHub commits GitHub license

A responsive country, state, city, and language dropdown for React (and now a phone input too!)

Installation

npm install --save react-country-state-dropdown

or using yarn:

yarn add react-country-state-dropdown

Demo

View the live demo.

Screenshot

image

Usage

It's very simple to use. The state can be managed in a controlled or uncontrolled manner. Here we are showing an example of controlled usage by assigning an initial value and an onChange handler. Note that the <StateDropdown /> requires a country input in order to display states for the selected country. <CityDropdown /> requires both a country and a state, and it's generally a good idea to use the option allowFreeFormText to allow city entries that aren't prepopulated in the dropdown.

import React, { useState } from 'react';
import { CountryDropdown, StateDropdown, CityDropdown, LanguagesDropdown, PhoneInput } from "react-country-state-dropdown";

const Example = () => {
  const [country, setCountry] = useState(null);
  const [state, setState] = useState(null);
  const [city, setCity] = useState(null);
  const [language, setLanguage] = useState(null);
  const [phone, setPhone] = useState(null);

  const handleSetCountry = (e, value) => setCountry(value);
  const handleSetState = (e, value) => setState(value);
  const handleSetCity = (e, value) => setCity(value);
  const handleSetLanguage = (e, value) => setLanguage(value);
  const handleSetPhone = (e, value) => setPhone(value);

  return (
    <div>
      <CountryDropdown clearable value={country} onChange={handleSetCountry} />
      <StateDropdown clearable country={country} value={state} onChange={handleSetState} />
      <CityDropdown clearable allowFreeFormText country={country} state={state} value={city} onChange={handleSetCity} />
      <LanguageDropdown searchable value={language} onChange={handleSetLanguage} />
      <PhoneInput clearable country={country} value={phone} onChange={handleSetPhone} />
    </div>);
};

Data

By default, the control will load the github hosted data files. Alternatively, you can download the data zip file and host it yourself. Simply unzip the JSON files, and supply the src property to each control to tell it where to download from.

Options

<Dropdown />

These attributes are common to all dropdowns. Rendering of the component is controllable for full customization.

ParameterRequired?DefaultTypeDescription
valueNo""stringThe currently selected value.
optionsNo[]arrayAn array of options available to the dropdown. These are populated automatically for the <CountryDropdown />, <StateDropdown />, <CityDropdown />, <LanguageDropdown /> controls.
srcNo"https://replaysmike.github.io/react-country-state-dropdown/data/"stringThe relative or absolute URL where the data files are hosted. Default is to serve from hosted CDN.
nameNo""stringThe name attribute of the generated select box.
idNo""stringThe ID of the generated select box. Not added by default.
classesNo""stringAny additional space-separated classes you want to add.
placeHolderNo""stringMessage displayed on the input/dropdown control when no input is selected.
emptyLabelNo"No items."stringMessage displayed when no items are available for selection in the menu.
stripedNofalsebooleanTrue to show the items in the list box with faint striping.
clearableNofalsebooleanTrue to show an X button to clear the selected value.
searchableNofalsebooleanTrue to allow text entry and filter the list by the searched value.
allowFreeFormTextNofalsebooleanTrue to allow entry of text that does not match any value in the options list.
disabledNofalsebooleanDisables the control.
onChangeNo-functionCallback that gets called when the user selects a value or text input changes.
onSelectNo-functionCallback that gets called when the user selects a value.
onSearchInputChangeNo-functionCallback that gets called when the text input is changed.
onRenderMenuNo-functionOverride the rendering of the menu container.
onRenderItemNo-functionOverride the rendering of the options item.
onRenderEmptyNo-functionOverride the rendering of the menu containers empty contents message.
onRenderInputNo-functionOverride the rendering of the input control.
onFocusNo-functionCallback that gets called when the input control receives focus.
onBlurNo-functionCallback that gets called when the input control loses focus.
classNameNo""stringAdd classes to the rcsd-dropdown
inputContainerClassNameNo""stringAdd classes to the rcsd-input
inputClassNameNo""stringAdd classes to the input element
menuClassNameNo""stringAdd classes to the menu
itemsClassNameNo""stringAdd classes to the items container
itemClassNameNo""stringAdd classes to the item
titleNo""stringThe title to use for the input control
widthNo-numberSet the width of the control
tabIndexNo-numberTabIndex of the control
formatterNo-functionCalled when formatting the selected value (if an object). Used primarily by dependent controls.

<CountryDropdown />

ParameterRequired?DefaultTypeDescription
placeHolderNo"Choose a country"stringMessage displayed on the input/dropdown control when no input is selected.
priorityNo['US', 'CA', 'MX']arrayAn array of ISO2 country codes (ex. 'US') to show at the top of the list.
removePrioritizedNofalsebooleanTrue to remove prioritized countries from the main list when searching.
showFlagsNotruebooleanTrue to show the country's flag.
nativeNotruebooleanTrue to show the country's native name instead of English name.
includeAlternateNofalsebooleanTrue to include alternate name (native name if native=false, English name if native=true).
prioritizedClassNameNo""stringAdd classes to the prioritized items container

<StateDropdown />

ParameterRequired?DefaultTypeDescription
placeHolderNo"Choose a state/province"stringMessage displayed on the input/dropdown control when no input is selected.
emptyLabelNo"No states available to select."stringLabel to display when no items are available.
noCountryLabelNo"Please select a country"stringLabel to display when no country is selected.
priorityNo[]arrayAn array of ISO2 state codes (ex. 'US') to show at the top of the list.
removePrioritizedNofalsebooleanTrue to remove prioritized countries from the main list when searching.
prioritizedClassNameNo""stringAdd classes to the prioritized items container

<CityDropdown />

ParameterRequired?DefaultTypeDescription
countryYes""string/id/objectThe country using a country object, name or ISO2 country code.
stateYes""string/id/objectThe state using a state object, name or state code.
placeHolderNo"Choose a city"stringMessage displayed on the input/dropdown control when no input is selected.
emptyLabelNo"No cities available to select."stringLabel to display when no items are available.
noCountryLabelNo"Please select a country"stringLabel to display when no country is selected.
noStateLabelNo"Please select a state/province"stringLabel to display when no state is selected.
priorityNo[]arrayAn array of ISO2 state codes (ex. 'US') to show at the top of the list.
removePrioritizedNofalsebooleanTrue to remove prioritized countries from the main list when searching.
prioritizedClassNameNo""stringAdd classes to the prioritized items container

<LanguageDropdown />

ParameterRequired?DefaultTypeDescription
placeHolderNo"Choose a language"stringMessage displayed on the input/dropdown control when no input is selected.
emptyLabelNo"No items."stringLabel to display when no items are available.
priorityNo['en']arrayAn array of ISO2 language codes (ex. 'en') to show at the top of the list.
removePrioritizedNofalsebooleanTrue to remove prioritized countries from the main list when searching.
prioritizedClassNameNo""stringAdd classes to the prioritized items container
showNativeNotruebooleanTrue to show native language name in parenthesis after the english name
useNativeNofalsebooleanTrue to show native language name instead of the english name

<PhoneInput />

ParameterRequired?DefaultTypeDescription
valueNo""stringThe currently selected value.
nameNo""stringThe name attribute of the generated select box.
countryYes""string/id/objectThe country using a country object, name or ISO2 country code.
idNo""stringThe ID of the generated select box. Not added by default.
classesNo""stringAny additional space-separated classes you want to add.
placeHolderNo"Enter a phone number"stringMessage displayed on the input/dropdown control when no input is selected.
priorityNo['US','CA','MX']arrayAn array of ISO2 country codes (ex. 'US') to show at the top of the list.
removePrioritizedNofalsebooleanTrue to remove prioritized countries from the main list when searching.
clearableNofalsebooleanTrue to show an X button to clear the selected value.
disabledNofalsebooleanDisables the control.
onChangeNo-functionCallback that gets called when the user selects a value.
onSearchInputChangeNo-functionCallback that gets called when the text input is changed.
prioritizedClassNameNo""stringAdd classes to the prioritized items container
dropdownInputClassNameNo""stringAdd classes to the dropdown input element

Examples

Here's an example of all the typical options being used.

import React, { useState } from 'react';
import { CountryDropdown, StateDropdown, CityDropdown, LanguagesDropdown, PhoneInput } from "react-country-state-dropdown";

const Example = () => {
  const [country, setCountry] = useState('US'); // can set a default value using the ISO2 code instead of the full country object
  const [state, setState] = useState(null);
  const [city, setCity] = useState(null);
  const [language, setLanguage] = useState(null);
  const [phone, setPhone] = useState(null);

  const handleSetCountry = (e, value) => setCountry(value);
  const handleSetState = (e, value) => setState(value);
  const handleSetCity = (e, value) => setCity(value);
  const handleSetLanguage = (e, value) => setLanguage(value);
  const handleSetPhone = (e, value) => setPhone(value);

  return (
    <div>
      <CountryDropdown clearable searchable striped value={country} onChange={handleSetCountry} />
      <StateDropdown clearable searchable striped country={country} value={state} onChange={handleSetState} />
      <CityDropdown clearable searchable striped allowFreeFormText country={country} state={state} value={city} onChange={handleSetCity} />
      <LanguageDropdown clearable searchable striped value={language} onChange={handleSetLanguage} />
      <PhoneInput clearable country={country} value={phone} onChange={handleSetPhone} />
    </div>);
};

Example on loading the JSON data from your own hosted location, located in the publicly accessible custom-geo-data folder of your own server.

import React, { useState } from 'react';
import { CountryDropdown } from "react-country-state-dropdown";

const Example = () => {
  const [country, setCountry] = useState(null);

  const handleSetCountry = (e, value) => {
    setCountry(value);
    console.log(value);
  };

  return (
    <div>
      <CountryDropdown clearable searchable striped value={country} onChange={handleSetCountry} src="/custom-geo-data" />
    </div>);
};

How to output the full country information.

import React, { useState } from 'react';
import { CountryDropdown } from "react-country-state-dropdown";

const Example = () => {
  const [country, setCountry] = useState(null);

  const handleSetCountry = (e, value) => {
    setCountry(value);
    console.log(value);
  };

  return (
    <div>
      <CountryDropdown clearable searchable striped value={country} onChange={handleSetCountry} />
    </div>);
};

Produces the output:

{
    "id": 233,
    "name": "United States",
    "iso3": "USA",
    "iso2": "US",
    "numeric_code": "840",
    "phone_code": 1,
    "capital": "Washington",
    "currency": "USD",
    "currency_name": "United States dollar",
    "currency_symbol": "$",
    "tld": ".us",
    "native": "United States",
    "region": "Americas",
    "subregion": "Northern America",
    "latitude": "38.00000000",
    "longitude": "-97.00000000",
    "emoji": "🇺🇸",
    "value": "United States"
}

How to output the full state information.

import React, { useState } from 'react';
import { StateDropdown } from "react-country-state-dropdown";

const Example = () => {
  const [state, setState] = useState(null);

  const handleSetState = (e, value) => {
    setState(value);
    console.log(value);
  };

  return (
    <div>
      <StateDropdown country='CA' clearable searchable striped value={state} onChange={handleSetState} />
    </div>);
};

Produces the output:

{
    "id": 875,
    "name": "British Columbia",
    "code": "BC",
    "value": "British Columbia"
}

Utility Functions

There are many functions that can be called to retrieve data, or format phone numbers.

getCountries(): Get an array of all countries.

getStates(): Get an array of all state/provinces.

getCities(): Get an array of all cities (very large list, see getCitiesForState()).

getLanguages(): Get an array of all languages.

getCountry(country): Get a country by name, ISO code, numerical id or object

getState(state, country): Get a state by name, ISO code, numerical id or object, country must be specified.

getStatesForCountry(country): Get an array of all state/provinces for a specified country.

getCity(city, state, country): Get a city by name, numerical id, or object, state and country must also be specified.

getCitiesForState(state, country): List all cities by state and country

getLanguage(language): Get a language by name, native name or ISO code

parsePartialNumber(phoneNumber, countryCode): Parse a partial phone number

parsePhoneNumber(phoneNumber, countryCode): Parse a phone number

formatPhoneNumber(phoneNumber, countryCode): Format a phone number

formatInternational(phoneNumber, countryCode): Format a phone number as the international E.164 format

isValidPhoneNumber(phoneNumber, countryCode): Check if a phone number is of valid format

getCountriesForPhoneNumber(phoneNumber): Get the countries for a E.164 format phone number