Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

react-phone-input-2

bl00mber1.2mMIT2.15.1TypeScript support: included

A react component to format phone numbers

react, phone, format, number, input, telephone, javascript, international, tel, localized, material, bootstrap, i18n

readme

React-Phone-Input-2

DONATIONS / FUNDING NEEDED

bitcoin bc1qa7q6gf9e06ssqrc46j5lekq886rlyyk6sdhjj0
ethereum 0x2b9429a7362a9b14f3d84a408d33caab29bdc225


Highly customizable phone input component with auto formatting.

npm version npm downloads PRs Welcome travis build

animation

Installation

npm install react-phone-input-2 --save

Usage

import PhoneInput from 'react-phone-input-2'
import 'react-phone-input-2/lib/style.css'

<PhoneInput
  country={'us'}
  value={this.state.phone}
  onChange={phone => this.setState({ phone })}
/>

available styles - style • high-res • material • bootstrap • semantic-ui • plain

Demo 1 (UI) - Demo 2 (CSS)

screenshot

Options

Name Type Description Example
country string initial country 'us' | 1
value string input state value
onlyCountries array country codes to be included ['cu','cw','kz']
preferredCountries array country codes to be at the top ['cu','cw','kz']
excludeCountries array array of country codes to be excluded ['cu','cw','kz']
placeholder string custom placeholder
inputProps object props to pass into the input
Booleans Default Description
autoFormat true on/off phone formatting
disabled false disable input and dropdown
disableDropdown false disable dropdown only
disableCountryCode false
enableAreaCodes false enable local codes for all countries
enableTerritories false enable dependent territories with population of ~100,000 or lower
enableLongNumbers false boolean/number
countryCodeEditable true
enableSearch false enable search in the dropdown
disableSearchIcon false hide icon for the search field
<PhoneInput
  inputProps={{
    name: 'phone',
    required: true,
    autoFocus: true
  }}
/>

Contents

Style

containerClass string class for container
inputClass string class for input
buttonClass string class for dropdown button
dropdownClass string class for dropdown container
searchClass string class for search field
containerStyle object styles for container
inputStyle object styles for input
buttonStyle object styles for dropdown button
dropdownStyle object styles for dropdown container
searchStyle object styles for search field

Events

onChange onFocus onBlur onClick onKeyDown

onChange(value, country, e, formattedValue)

Country data object not returns from onKeyDown event

Data Type Description
value/event string/object event or the phone number
country data object country object { name, dialCode, countryCode (iso2) }

Regions

Name Type Description
regions array/string to show countries only from specified regions
Regions
['america', 'europe', 'asia', 'oceania', 'africa']
Subregions
['north-america', 'south-america', 'central-america', 'carribean', 'eu-union', 'ex-ussr', 'ex-yugos', 'baltic', 'middle-east', 'north-africa']
<PhoneInput
  country='de'
  regions={'europe'}
/>

<PhoneInput
  country='us'
  regions={['north-america', 'carribean']}
/>

Predefined localization

es Spanish, de Deutsch, ru Russian, fr French
jp Japanese, cn Chinese, pt Portuguese, it Italian
ir Iranian, ar Arabic, tr Turkish, id Indonesian
hu Hungarian, pl Polish, ko Korean

import es from 'react-phone-input-2/lang/es.json'

<PhoneInput
  localization={es}
/>

Local area codes

<PhoneInput
  enableAreaCodes={true}
  enableAreaCodes={['us', 'ca']}
  enableAreaCodeStretch
/>

Flexible mask

If enableAreaCodeStretch is added, the part of the mask with the area code will not stretch to length of the respective section of phone mask. Example: +61 (2), +61 (02)

Custom masks

<PhoneInput
  onlyCountries={['fr', 'at']}
  masks={{fr: '(...) ..-..-..', at: '(....) ...-....'}}
/>

Custom area codes

<PhoneInput
  onlyCountries={['gr', 'fr', 'us']}
  areaCodes={{gr: ['2694', '2647'], fr: ['369', '463'], us: ['300']}}
/>

Other props

defaultMask ... ... ... ... ..
alwaysDefaultMask false
prefix +
searchPlaceholder 'search'
searchNotFound 'No entries to show'
copyNumbersOnly true
renderStringAsFlag string
autocompleteSearch false
jumpCursorToEnd false
priority {{ca: 0, us: 1, kz: 0, ru: 1}}
enableClickOutside true
showDropdown false
defaultErrorMessage string
specialLabel string
disableInitialCountryGuess false
disableCountryGuess false

Custom localization

<PhoneInput
  onlyCountries={['de', 'es']}
  localization={{de: 'Deutschland', es: 'España'}}
/>

<PhoneInput
  onlyCountries={['de', 'es']}
  localization={{'Germany': 'Deutschland', 'Spain': 'España'}}
/>

Preserve countries order

<PhoneInput
  onlyCountries={['fr', 'at']}
  preserveOrder={['onlyCountries', 'preferredCountries']}
/>

Guides

Phone without dialCode

handleOnChange(value, data, event, formattedValue) {
  this.setState({ rawPhone: value.slice(data.dialCode.length) })
}

Check validity of the phone number

isValid(value, country, countries, hiddenAreaCodes)

<PhoneInput
  isValid={(value, country) => {
    if (value.match(/12345/)) {
      return 'Invalid value: '+value+', '+country.name;
    } else if (value.match(/1234/)) {
      return false;
    } else {
      return true;
    }
  }}
/>
import startsWith from 'lodash.startswith';

<PhoneInput
  isValid={(inputNumber, country, countries) => {
    return countries.some((country) => {
      return startsWith(inputNumber, country.dialCode) || startsWith(country.dialCode, inputNumber);
    });
  }}
/>

Clear country

To clear country, pass null as value.

Dynamic placeholder

<summary>Show</summary>
const phoneCountryFormat = useMemo(() => phoneCountry?.format || undefined, [phoneCountry]);
const placeholder = useMemo(() => {
  if (phoneCountryFormat) {
    const words = phoneCountryFormat.split(' ');
    words.shift(); // I'm using only local numbers so here I remove the country code from the format
    let text = words.join(' ');
     // first digit is special on french numbers, these 3 lines could be removed
    if (country === 'fr') {
      text = text.replace('.', '6');
    }
    while (text.indexOf('.') > -1) {
      text = text.replace('.', `${Math.min(9, Math.max(1, Math.floor(Math.random() * 10)))}`);
    }
    return text;
  }
  return '';
}, [phoneCountryFormat, country]);

CDN

<script src="https://unpkg.com/react-phone-input-2@2.x/dist/lib.js"></script>

Contributing

  • Code style changes not allowed
  • Do not create issues about incorrect or missing country masks (of already present countries) or absent area codes (they will be closed). Only create issues if the subject is an actual mechanism that is not present in the component. Otherwise create a PR with a link that proves the correctness of your newly suggested mask or list of area codes
  • Do not send new languages

License

GitHub license

Based on react-phone-input

Make sure you donated for lib maintenance Donate

changelog

2.15.0 (February 3, 2022)

  • Hungarian, Polish, Korean translation
  • numerous fixes

2.13.8 (August 25, 2020)

  • specialLabel, disableCountryGuess
  • Add some missing flags to css
  • Minor fixes

2.13.7 (June 27, 2020)

2.13.1 (April 15, 2020)

  • enableAreaCodeStretch to handle area codes of different length on the same country
  • null passed as value will clear country, empty string will clear prefix
  • enableClickOutside to disable dropdown close handler
  • showDropdown to allow initially opened dropdowns
  • Always return unformatted value as 1st argument and formatted as 4th in onChange
  • Search by dialCode
  • searchNotFound to modify text showed when no entry is found
  • Do not use prefix and dialCode in custom masks
  • Add hiddenAreaCodes which is the array of disabled area codes used to compute correct country
  • Enable event propagation for onEnterKeyPress
  • Validation defaultErrorMessage on the top of the input
  • Derive errorMessage from isValid handler
  • Mexican area codes @fleetofthemalden
  • Australia area codes
  • Typescript support

2.12.1 (March 11, 2020)

  • priority, alwaysDefaultMask
  • Custom tabIndex
  • Replace id usage to classes to avoid warnings @J-theGit
  • Dynamic mask creation
  • Move dependent territories to external file, add enableTerritories @gillerg8

2.11.0 (December 4, 2019)

  • Add languages: jp, cn, pt, it, ir, ar, id
  • Replace disableAreaCodes to enableAreaCodes
  • defaultCountrycountry
  • enableSearchFieldenableSearch
  • Search update, search countries firstly using iso2 codes
  • Set countries using dialCode
  • Add Kosovo, subregions: ex-yugos, baltic
  • Add defaultMask, prefix
  • Copy number from input without formatting
  • Select whole number when double click
  • Pass event object to onChange handler
  • Style update: style.css high-res.css material.css bootstrap.css semantic-ui.css plain.css

2.10.0 (September 18, 2019)

  • Add languages: es, de, ru, fr
  • Custom areaCodes
  • Search localized country name #123
  • renderStringAsFlag to show string instead of flag
  • Fix input freezing on area codes #119
  • Add preserveOrder #109
  • Better keyboard support
  • Make lib work inside shadow DOM #105 @newying61
  • IE Polyfyll startswith #102

2.9.3 (April 8, 2019)

  • SSR support (removed references to browser objects)
  • Change importing method
  • defaultCountry update fix #70
  • Add disableSearchIcon, searchStyle props
  • Tests

2.8.0 (February 20, 2019)

  • Custom phone masks
  • Localization using iso2 codes
  • Upgrade dependencies & webpack #65 @jnsdls
  • Remove lodash #44
  • Keep detection of area codes with disableAreaCodes #49
  • Drop setSelectionRange() check #50
  • Customizable placeholder for search field
  • Update phone masks
  • Fix first number cutting #72

2.7.1 (November 29, 2018)

  • Styles update, fix SearchField autoFocus
  • SearchField @awthwathje

2.6.1 (September 26, 2018)

  • Pass props into the input via inputExtraProps
  • Remove autoFocus, name, required props

2.5.1 (July 26, 2018)

  • Add autoFocus prop to input @mikesholiu
  • Focus and highlight preferred country
  • Abstracts global document and document related properties @Alex-ray

2.4.1 (July 1, 2018)

  • Fix backspace
  • Always show right bracket
  • Add containerStyle prop
  • Fix areaCodes doesn't change when same country selected
  • Make country code not editable by passing prop countryCodeEditable @HasanShehryarJaffri

2.3.0 (May 27, 2018)

  • Add localization feature
  • Add classname to the main container
  • Add custom class configurations @Alex-ray

2.2.1 (March 15, 2018)

  • Add masks for disableCountryCode attribute
  • Add attribute to enable non-mask phone lengths
  • Make phone formatter to reject non-mask phone lengths

2.1.1 (January 23, 2018)

  • Add country object to be return to props functions @shaypeleg1
  • SearchCountry error fix
  • Add disableDropdown and disableCountryCode

2.0.0 (September 4, 2017)

  • Add feature to select from regions
  • Add regions and encapsulation
  • Styles changed, styles customization
  • Hide dropdown by click outside
  • String refs replaced by callback refs
  • Hide flag by default, custom placeholder
  • Add property to disable area codes
  • Fix preferred countires dropdown bug
  • Auto-update flag if value field used, caret right-auto-align