react-phone-input-2

repository·master·Indexed 21 days ago

https://github.com/bl00mber/react-phone-input-2

A highly customizable React component for phone number input featuring automatic formatting, country selection with flags, and support for various regions and local area codes. It includes features for custom masks, localization, and validation via the isValid prop.

Tokens
2.7K
Snippets
9
Records
13
Agent score
27%

What's inside react-phone-input-2

  1. Use custom masks and area codes

    master

    You can define specific input masks and area codes for certain countries.

    Custom Masks

    Use the masks prop to provide a mapping of country codes to mask patterns.

    Custom Area Codes

    Use the areaCodes prop to provide a mapping of country codes to arrays of valid area codes.

    Local Area Codes

    Enable local area code support using enableAreaCodes. You can pass an array of country codes to limit this feature to specific countries and use enableAreaCodeStretch to prevent the mask from stretching to the full length of the area code section.

    <PhoneInput
      onlyCountries={['fr', 'at']}
      masks={{fr: '(...) ..-..-..', at: '(....) ...-....'}}
    />
    
    <PhoneInput
      enableAreaCodes={true}
      enableAreaCodes={['us', 'ca']}
      enableAreaCodeStretch
    />
    
    <PhoneInput
      onlyCountries={['gr', 'fr', 'us']}
      areaCodes={{gr: ['2694', '2647'], fr: ['369', '463'], us: ['300']}}
    />
  2. Apply localization to PhoneInput

    master

    You can localize the component using predefined language files or custom localization objects.

    Predefined Localization

    Import language JSON files from react-phone-input-2/lang/ (e.g., es, de, ru, fr, jp, cn, pt, it, ir, ar, tr, id, hu, pl, ko).

    Custom Localization

    Pass a mapping object to the localization prop where keys are country names or codes and values are the translated strings.

    import es from 'react-phone-input-2/lang/es.json'
    
    <PhoneInput localization={es} />
    
    // Or custom mapping
    <PhoneInput
      onlyCountries={['de', 'es']}
      localization={{de: 'Deutschland', es: 'España'}}
    />
    import es from 'react-phone-input-2/lang/es.json'
    
    <PhoneInput
      localization={es}
    />
  3. Configure PhoneInput options

    master

    The PhoneInput component accepts several configuration options to control country selection, formatting, and behavior.

    Country Selection

    • country: Initial country (e.g., 'us' or 1).
    • onlyCountries: Array of country codes to be included (e.g., ['cu','cw','kz']).
    • preferredCountries: Array of country codes to appear at the top of the list.
    • excludeCountries: Array of country codes to be excluded.
    • regions: Show countries only from specified regions (e.g., 'europe', 'asia') or subregions (e.g., 'north-america', 'eu-union').

    Behavior and Formatting

    • autoFormat: Boolean (default true) to toggle on/off phone formatting.
    • disabled: Boolean (default false) to disable both the input and the dropdown.
    • disableDropdown: Boolean (default false) to disable only the dropdown.
    • enableSearch: Boolean (default false) to enable searching within the dropdown.
    • enableAreaCodes: Boolean (default false) to enable local codes for all countries.
    • enableLongNumbers: Boolean or number to allow longer phone numbers.
    • countryCodeEditable: Boolean (default true) to allow editing the country code.
    • inputProps: Object containing props to pass directly into the underlying HTML input element.
    <PhoneInput
      inputProps={{
        name: 'phone',
        required: true,
        autoFocus: true
      }}
    />
  4. Customize PhoneInput styles

    master

    You can customize the appearance of the component using CSS classes or inline styles for various sub-elements.

    CSS Classes

    • containerClass: Class for the main container.
    • inputClass: Class for the input field.
    • buttonClass: Class for the dropdown button.
    • dropdownClass: Class for the dropdown container.
    • searchClass: Class for the search field.

    Inline Styles

    Use the following keys to pass style objects:

    • containerStyle
    • inputStyle
    • buttonStyle
    • dropdownStyle
    • searchStyle
  5. Basic usage of PhoneInput

    master

    To use the component, import PhoneInput and its required CSS file. You should manage the phone number in your component's state and update it via the onChange callback.

    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 })}
    />
  6. Validate phone numbers with isValid

    master

    The isValid prop allows you to provide a custom validation function. The function receives (value, country, countries) and should return true if valid, or false/a string if invalid.

    <PhoneInput
      isValid={(value, country) => {
        if (value.match(/12345/)) {
          return 'Invalid value: '+value+', '+country.name;
        } else if (value.match(/1234/)) {
          return false;
        } else {
          return true;
        }
      }}
    />
  7. Handle PhoneInput events

    master

    The component supports several event listeners:

    • onChange: Triggered when the value changes. Signature: onChange(value, country, e, formattedValue).
      • value: The phone number string.
      • country: An object containing { name, dialCode, countryCode (iso2) }.
      • e: The event object.
      • formattedValue: The formatted phone number string.
    • onFocus
    • onBlur
    • onClick
    • onKeyDown (Note: The country data object is not returned from the onKeyDown event).
  8. Configure PhoneInput styling and classes

    master

    The component allows granular control over its visual presentation via styles and CSS classes:

    Styles (Objects):

    • containerStyle: Style for the outer wrapper.
    • inputStyle: Style for the text input.
    • buttonStyle: Style for the flag/dropdown button.
    • dropdownStyle: Style for the country list container.
    • searchStyle: Style for the search input.

    CSS Classes (Strings):

    • className: Applied to the outer container.
    • containerClass: Custom class for the container.
    • inputClass: Custom class for the input.
    • buttonClass: Custom class for the flag button.
    • dropdownClass: Custom class for the dropdown list.
    • searchClass: Custom class for the search box.
    • inputProps: An object passed directly to the underlying <input> element.
  9. Configure PhoneInput search and behavior

    master

    Customize how the input behaves and how users search for countries:

    • enableSearch: Enables a search box within the dropdown.
    • searchPlaceholder: Placeholder text for the search box.
    • searchNotFound: Text displayed when no countries match the search.
    • disableSearchIcon: Hides the magnifying glass icon in the search box.
    • autocompleteSearch: Whether to enable browser autocomplete on the search box.
    • autoFormat: Automatically formats the number as the user types (default: true).
    • countryCodeEditable: Allows the user to edit the dial code directly in the input (default: true).
    • disableCountryGuess: Disables the automatic detection of the country based on the dial code entered.
    • disableInitialCountryGuess: Disables detecting the country from the initial value.
    • jumpCursorToEnd: Automatically moves the cursor to the end of the input on focus (default: true).
  10. Configure PhoneInput country selection

    master

    You can control which countries appear in the dropdown using the following props:

    • country: The initial selected country. Can be an ISO2 string (e.g., 'us') or a dial code (e.g., 1).
    • onlyCountries: An array of ISO2 strings to restrict the list to specific countries.
    • preferredCountries: An array of ISO2 strings to show at the top of the list.
    • excludeCountries: An array of ISO2 strings to remove from the list.
    • regions: A string or array of strings to filter countries by region.
    • preserveOrder: An array of ISO2 strings to maintain a specific order in the list.
    <PhoneInput
      onlyCountries={['us', 'gb', 'ca']}
      preferredCountries={['us']}
      excludeCountries={['ca']}
      country='us'
    />
  11. Configure regions and subregions

    master

    Filter the available countries by specifying regions as a string or an array of strings.

    Available Regions:

    • ['america', 'europe', 'asia', 'oceania', 'africa']

    Available 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']}
    />