react-international-phone

repository·master·Indexed 19 days ago

https://github.com/ybrusentsov/react-international-phone

An international phone input component for React (v4.8.0) featuring country guessing, automatic formatting, and easy customization. It provides a highly customizable PhoneInput component with support for custom country lists, dial code prefilling, and mask formatting. The library includes a comprehensive API for managing phone state, a ref-based interface for programmatic country selection, and CSS variables for styling.

Tokens
16.5K
Snippets
47
Records
68
Agent score
64%

What's inside react-international-phone

  1. Integrate react-international-phone with UI libraries

    master

    To build a custom phone input using third-party UI libraries (like Material UI, Ant Design, or Chakra UI), you should combine three core elements:

    1. An input component from your UI library (e.g., Material UI's TextField).
    2. The usePhoneInput hook to manage the phone number state and logic.
    3. The CountrySelector subcomponent (or a custom implementation using FlagImage and parseCountry) to handle country selection.

    This approach allows you to maintain the visual style of your existing design system while leveraging the phone validation and formatting logic of react-international-phone.

    // Conceptual pattern for custom UI integration
    const { 
      inputValue, 
      handlePhoneValueChange, 
      inputRef, 
      country, 
      setCountry 
    } = usePhoneInput({
      defaultCountry: 'us',
      value,
      countries: defaultCountries,
      onChange: (data) => onChange(data.phone),
    });
    
    // Use inputValue and handlePhoneValueChange in your UI component's value and onChange props
    <YourUIComponent 
      value={inputValue} 
      onChange={handlePhoneValueChange} 
      inputRef={inputRef} 
    />
  2. Understand the PhoneInput component structure

    master

    The PhoneInput component is a composite component made up of four primary subcomponents. If you need to build a fully custom phone input UI, you can reuse these individual pieces instead of using the default PhoneInput wrapper.

    The main parts are:

    • Input component: A base HTML input element.
    • CountrySelector component: The UI element used to trigger country selection.
    • CountrySelectorDropdown component: The dropdown menu containing the list of countries.
    • DialCodePreview component: The element that displays the selected country's dial code.
    • FlagImage component: A utility component used to display country flags.
  3. How to validate phone numbers

    master

    Note that react-international-phone no longer provides built-in validation functionality. To validate phone numbers, it is recommended to use the google-libphonenumber library.

    You can create a validator function by using PhoneNumberUtil.getInstance() to parse the input and check its validity using isValidNumber.

    import { PhoneNumberUtil } from 'google-libphonenumber';
    
    const phoneUtil = PhoneNumberUtil.getInstance();
    
    const isPhoneValid = (phone: string) => {
      try {
        return phoneUtil.isValidNumber(phoneUtil.parseAndKeepRawInput(phone));
      } catch (error) {
        return false;
      }
    };
  4. Build a custom phone input using Subcomponents

    master

    To create a custom phone input experience that deviates from the default PhoneInput styling or behavior, you can import and compose the following subcomponents manually:

    • CountrySelector
    • CountrySelectorDropdown
    • DialCodePreview
    • FlagImage

    This allows you to place the country selector and the input field in different parts of your layout or apply custom styling to each individual piece.

  5. Modify the country list for PhoneInput

    master

    You can customize the available countries in the PhoneInput component by providing a custom countries array. You can achieve this by importing defaultCountries and applying transformations like filter, map, or sorting. To easily manipulate country data, use the parseCountry helper to convert the default array format into a more manageable object.

    import { useState } from 'react';
    import {
      PhoneInput,
      defaultCountries,
      parseCountry,
    } from 'react-international-phone';
    
    // Filter to only show specific countries
    const countries = defaultCountries.filter((country) => {
      const { iso2 } = parseCountry(country);
      return ['us', 'ua', 'gb'].includes(iso2);
    });
    
    const App = () => {
      const [phone, setPhone] = useState('');
    
      return (
        <PhoneInput
          defaultCountry="ua"
          phone={phone}
          onChange={setPhone}
          countries={countries}
        />
      );
    };
  6. Migrate usePhoneInput return properties

    master

    In v4, the properties returned by the usePhoneInput hook have been renamed to better reflect their purpose. If you were using the hook, you must update your variable references:

    • phone is now inputValue (the string rendered inside the input element).
    • e164Phone is now phone (the phone number in E.164 format).

    Warning: The hook still returns a property named phone, but its meaning has changed from the raw input value to the E.164 formatted value.

    // v3 usage (conceptual)
    const { phone, e164Phone } = usePhoneInput();
    
    // v4 usage
    const { inputValue, phone } = usePhoneInput();
  7. Use the usePhoneInput hook to format existing inputs

    master

    The usePhoneInput hook allows you to add phone formatting capabilities to your own custom input components. Instead of using a pre-built component, you use the hook to manage the phone state and receive the necessary handlers to connect to your input element.

    To integrate the hook with an input, you must use:

    1. inputValue: The formatted string to pass to the input's value prop.
    2. handlePhoneValueChange: The function to pass to the input's onChange prop.
    3. inputRef: The ref to pass to the input element to manage caret position, focus, and undo/redo functionality.
    import { usePhoneInput } from 'react-international-phone';
    
    const MyCustomInput = () => {
      const {
        inputValue,
        phone,
        country,
        setCountry,
        handlePhoneValueChange,
        inputRef,
      } = usePhoneInput({
        defaultCountry: 'us',
        value: '+1 (234)',
        onChange: ({ phone, inputValue, country }) => {
          // handle changes here
        },
      });
    
      return (
        <input
          ref={inputRef}
          value={inputValue}
          onChange={handlePhoneValueChange}
        />
      );
    };
  8. Enable type-aware lint rules in ESLint

    master

    For production applications, it is recommended to enable type-aware linting in your ESLint configuration.

    1. Update parserOptions in your ESLint config:
    parserOptions: {
      ecmaVersion: 'latest',
      sourceType: 'module',
      project: ['./tsconfig.json', './tsconfig.node.json'],
      tsconfigRootDir: __dirname,
    },
    1. Update your extends list:
    • Replace plugin:@typescript-eslint/recommended with plugin:@typescript-eslint/recommended-type-checked or plugin:@typescript-eslint/strict-type-checked.
    • Optionally add plugin:@typescript-eslint/stylistic-type-checked.
    • Install eslint-plugin-react and add plugin:react/recommended and plugin:react/jsx-runtime to the extends list.