Skip to main content

usePhoneInput

usePhoneInput is a hook for providing phone formatting to existing input components.

Use phone (as value), handlePhoneValueChange (as onChange callback) and inputRef (as passed ref) to handle input.

Usage Example

// import { usePhoneInput } from 'react-international-phone';

const { country, setCountry, phone, handlePhoneValueChange, inputRef } =
usePhoneInput({
defaultCountry: 'us',
value: '+1 (234)',
onChange: ({ phone, country }) => {
// make something on change
},
});

Hook arguments

ArgumentTypeDescriptionDefault value
defaultCountry *CountryIso2Default country value (iso2).
valuestringPhone value.""
countriesCountryData[]An array of available countries to select (and guess).defaultCountries
prefixstringPrefix for phone value."+"
defaultMaskstringThis mask will apply on countries that does not have specified mask."............" (12 chars)
charAfterDialCodestringChar that renders after country dial code.
historySaveDebounceMSnumberSave value to history if there were not any changes in provided milliseconds timeslot.
Undo/redo (ctrl+z/ctrl+shif+z) works only with values that are saved in history.
200
disableCountryGuessbooleanDisable country guess on value change.
- onCountryGuess callback would not be called.
false
disableDialCodePrefillbooleanDisable dial code prefill on initialization.
Dial code prefill works only when "empty" phone value have been provided.
false
forceDialCodebooleanAlways display the dial code.
Dial code can't be removed/changed by keyboard events, but it can be changed by pasting another country phone value.
false
disableDialCodeAndPrefixbooleanPhone value will not include passed dialCode and prefix if set to true.
- disableCountryGuess value will be ignored and set to true.
- forceDialCode value will be ignored and set to false.
false
onChange(data: { phone: string; country: CountryIso2 }) => voidCallback that calls on phone changeundefined

Returned values

ValueTypeDescription
phonestringFormatted phone string.
handlePhoneValueChange(e: React.ChangeEvent<HTMLInputElement>) => stringChange handler for input component.
inputRefReact.RefObject<HTMLInputElement>Ref object for input component (handles caret position, focus and undo/redo).
countryCountryIso2Current country iso code.
setCountry(country: CountryIso2) => voidCountry setter.