react-phone-number-input

repository·master·Indexed 21 days ago

https://github.com/catamphetamine/react-phone-number-input

A React component for international telephone number input that handles country selection, flags, and E.164 formatting. It provides a feature-complete PhoneInput component with a country selector, a bare-bones unstyled input for custom UIs, and a React Native compatible version. The library includes utility functions for formatting, parsing, and validating phone numbers, as well as support for localization and customizable CSS variables.

Tokens
18.7K
Snippets
65
Records
96
Agent score
75%

What's inside react-phone-number-input

  1. Understand Country Codes in this library

    master

    This library uses libphonenumber-js's definition of "country code", which includes both official ISO 3166-1 alpha-2 codes and some unofficial codes.

    Caution: If your application expects strictly official ISO country codes, you may need to manually transform unofficial codes returned by this library to their most suitable official parent country code.

    To verify if a specific two-letter code is supported, use the isSupportedCountry() function.

  2. Optimize bundle size using different metadata sets

    master

    The package allows you to choose between different metadata sets to balance phone number validation capabilities against bundle size. The choice depends on whether you need strict validation or phone number type detection (e.g., distinguishing 'mobile' from 'fixed line').

    Metadata Options

    • min (Default): Smallest set (~80KB). Use when you only need basic length validation via isPossiblePhoneNumber() and do not need strict digit validation or type detection.
    • max: Complete set (~145KB). Use when you need strict validation via isValidPhoneNumber() or need to detect phone number types.
    • mobile: Mobile-only set (~95KB). Use when you want max capabilities but only intend to accept mobile numbers. It can handle non-mobile numbers, but validation might return false or fail to determine the type.
    • custom: Advanced. Use when you want to generate your own metadata (via libphonenumber-js) to support only specific countries and minimize bundle size further.
  3. Integrate with react-hook-form

    master

    The library provides dedicated components for seamless integration with react-hook-form. You can pass the control object directly to the component or wrap your form in a <FormProvider/>.

    // "Without country select" component.
    import PhoneInput from "react-phone-number-input/react-hook-form-input"
    
    // "With country select" component.
    import PhoneInputWithCountry from "react-phone-number-input/react-hook-form"
    
    import { useForm } from "react-hook-form"
    
    export default function Form() {
      const {
        control,
        handleSubmit
      } = useForm()
    
      return (
        <form onSubmit={handleSubmit(...)}>
          <PhoneInput
            name="phoneInput"
            control={control}
            rules={{ required: true }} />
    
          <PhoneInputWithCountry
            name="phoneInputWithCountrySelect"
            control={control}
            rules={{ required: true }} />
    
          <button type="submit">
            Submit
          </button>
        </form>
      )
    }
  4. Localize the PhoneInput component

    master

    You can translate the component by passing a labels object to the PhoneInput. The library provides pre-packaged translations in the react-phone-number-input/locale directory.

    A translation object must include country names (including unofficial codes like AC, TA, XK, and ZZ) and specific keys for UI elements:

    • country: used for the country <select/> aria-label.
    • phone: label for the phone number input.
    • ext: label for the extension input.
    • ZZ: label for "International" (when no country is selected).
    import russianLabels from 'react-phone-number-input/locale/ru'
    
    <PhoneInput labels={russianLabels} .../>

    Translation Object Format:

    {
      "country": "Phone number country",
      "phone": "Phone",
      "ext": "ext.",
      "RO": "Romania",
      "RS": "Serbia",
      "RU": "Russia",
      "ZZ": "International"
    }
  5. Select the correct import path based on metadata and component type

    master

    To use a specific metadata set, you must import from the corresponding sub-package. The import path depends on whether you want the component with or without a country selector.

    With Country Select

    MetadataImport Path
    minreact-phone-number-input
    maxreact-phone-number-input/max
    mobilereact-phone-number-input/mobile
    customreact-phone-number-input/core

    Without Country Select

    MetadataImport Path
    minreact-phone-number-input/input
    maxreact-phone-number-input/input-max
    mobilereact-phone-number-input/input-mobile
    customreact-phone-number-input/input-core
  6. Use custom metadata with core components

    master

    If you have generated a custom metadata set using libphonenumber-js, you must use the core sub-packages. These sub-packages do not come with pre-packaged metadata and require you to pass a metadata property manually.

    Import paths for custom metadata:

    • With country select: react-phone-number-input/core
    • Without country select: react-phone-number-input/input-core
  7. Include react-phone-number-input via CDN

    master

    You can include the library directly in a web page using a <script> tag from a CDN like unpkg.com.

    Choose the bundle that matches your metadata needs:

    • react-phone-number-input.js: Default (min metadata).
    • react-phone-number-input-max.js: Max metadata.
    • react-phone-number-input-mobile.js: Mobile metadata.
    • react-phone-number-input-input.js: Without country select (min metadata).

    Note: You must also include the style.css for the component to render correctly.

    <!-- Default ("min" metadata) -->
    <script src="https://unpkg.com/react-phone-number-input@3.x/bundle/react-phone-number-input.js"></script>
    
    <!-- Styles -->
    <link rel="stylesheet" href="https://unpkg.com/react-phone-number-input@3.x/bundle/style.css"/>
    
    <script>
      var PhoneInput = window.PhoneInput.default
    </script>
  8. Use the PhoneInput component with country select

    master

    The PhoneInput component (imported from react-phone-number-input) is the most feature-complete variant. It includes a country selector with flags and labels on the left side of the input field.

    Requirements:

    • You must import the CSS styles: import 'react-phone-number-input/style.css'.

    Core Props:

    • value: The phone number in E.164 format (e.g., "+12133734253"). Falsy values (undefined, null, or "") are treated as no value.
    • onChange(value): A callback function called when the user types or clears the input. The argument is the parsed phone number in E.164 format, or undefined if the field is cleared.
    • defaultCountry (optional): A two-letter country code (e.g., "US") to set the initial country selection.
    • onCountryChange (optional): A callback function called when the user selects a different country, receiving the new country code as an argument.
    • Any other standard HTML <input> props (like placeholder) are passed through to the underlying input element.
    // CSS styles
    import 'react-phone-number-input/style.css'
    
    import PhoneInput from 'react-phone-number-input'
    
    function Example() {
      const [value, setValue] = useState()
      return (
        <PhoneInput
          placeholder="Enter phone number"
          value={value}
          onChange={setValue}
        />
      )
    }
  9. Create a custom country select with PhoneInput

    master

    You can build a custom country selection UI by using the exported getCountries() and getCountryCallingCode(country) functions alongside the PhoneInput/input component. This allows you to decouple the country selection from the phone number input field.

    import PropTypes from 'prop-types'
    import { getCountries, getCountryCallingCode } from 'react-phone-number-input'
    
    const CountrySelect = ({ value, onChange, labels, ...rest }) => (
      <select
        {...rest}
        value={value}
        onChange={event => onChange(event.target.value || undefined)}>
        <option value="">
          {labels['ZZ']}
        </option>
        {getCountries().map((country) => (
          <option key={country} value={country}>
            {labels[country]} +{getCountryCallingCode(country)}
          </option>
        ))}
      </select>
    )
    
    CountrySelect.propTypes = {
      value: PropTypes.string,
      onChange: PropTypes.func.isRequired,
      labels: PropTypes.objectOf(PropTypes.string).isRequired
    }
  10. Customize the PhoneInput component

    master

    The <PhoneInput/> component (with country select) supports several customization properties to override default behavior or appearance.

    Note on Bundle Size: All default values are included in your application bundle by default. To exclude default metadata and labels to save space, import the component from the react-phone-number-input/core subpackage instead of the main react-phone-number-input package.

    Available Customization Props:

    • metadata: Custom libphonenumber-js metadata (e.g., to limit the subset of supported countries).
    • labels: Custom translation messages for country names and other labels.
    • inputComponent: Custom phone number <input/> component.
    • countrySelectComponent: Custom country <select/> component.
    • internationalIcon: Custom icon component for the 'International' state.
    • flagComponent: Custom flag icon component.
    • countrySelectProps.arrowComponent: Custom arrow/dropdown icon for the country selector.