### Labels Example Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/types.md An example demonstrating how to define custom labels for countries and UI elements. ```typescript const labels: Labels = { US: 'United States', RU: 'Russia', ZZ: 'International', country: 'Country', phone: 'Phone' } ``` -------------------------------- ### Custom Input Component Example Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/input-basic.md Shows how to integrate a custom input component with InputBasic. The example provides a styled input element that receives all necessary props. ```javascript const CustomInputComponent = React.forwardRef((props, ref) => ( )) ``` -------------------------------- ### Install react-phone-number-input Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/INDEX.md Install the library using npm. This also requires React 16.8+ and react-dom 16.8+. ```bash npm install react-phone-number-input --save ``` -------------------------------- ### Full Example of Responsive Phone Input Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/styling-and-customization.md This snippet demonstrates a complete, responsive phone input field with custom styling. It includes necessary imports and basic state management for the input value. Use this as a starting point for integrating the component with custom styles. ```javascript import React, { useState } from 'react' import PhoneInput from 'react-phone-number-input' import 'react-phone-number-input/style.css' import './phone-input-custom.css' function ResponsivePhoneInput() { const [value, setValue] = useState() return (
) } ``` -------------------------------- ### Real-World Example with PhoneInput Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/use-external-ref.md Illustrates using a ref with the PhoneInput component and a button to focus the input. ```javascript import React, { useRef } from 'react' import PhoneInput from 'react-phone-number-input/input' function PhoneForm() { const inputRef = useRef() const handleFocus = () => { inputRef.current?.focus() } return (
) } ``` -------------------------------- ### Full Migration Example: v2 to v3 Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/migration-guide.md Provides a complete example of migrating a form component from v2 to v3, applying the discussed changes in imports, props, and placeholders. ```javascript import React, { useState } from 'react' import PhoneInput from 'react-phone-number-input' import 'react-phone-number-input/style.css' function MyForm() { const [value, setValue] = useState() return ( ) } ``` ```javascript import React, { useState } from 'react' import PhoneInput from 'react-phone-number-input' import 'react-phone-number-input/style.css' function MyForm() { const [value, setValue] = useState() return ( ) } ``` -------------------------------- ### v2 Import Example Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/migration-guide.md This is how you would import the PhoneInput component in v2. ```javascript // v2 import PhoneInput from 'react-phone-number-input' ``` -------------------------------- ### Basic CountrySelect Usage Example Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/country-select.md Demonstrates how to use the basic CountrySelect component with state management for country selection. ```javascript import React, { useState } from 'react' import CountrySelect from 'react-phone-number-input' function MyComponent() { const [country, setCountry] = useState() const options = [ { value: 'US', label: 'United States' }, { value: 'RU', label: 'Russia' }, { value: 'FR', label: 'France' } ] return ( ) } ``` -------------------------------- ### InputSmart Component Usage Example Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/input-smart.md A basic example demonstrating how to use the InputSmart component with state management for the phone number digits. It includes country and input format configurations. ```javascript import React, { useState } from 'react' import InputSmart from 'react-phone-number-input/input-core' function MyComponent() { const [phoneDigits, setPhoneDigits] = useState('') return ( ) } ``` -------------------------------- ### InputSmart Step-by-Step Behavior Example Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/input-smart.md A conceptual walkthrough of how InputSmart processes user input character by character, demonstrating the parsing, formatting, and caret positioning steps involved. ```javascript // User types: "213" // For country "US" with format "NATIONAL": Step 1: Parse character "2" -> { digitsOnly: "2", ... } Step 2: Format with AsYouType formatter.input(prefix + "2") -> Displays: "(2" Step 3: Get template formatter.getTemplate() -> Template: "(XXX) XXX-XXXX" Step 4: Calculate caret position -> Position caret after "(2" but before "X" ... repeat for each character typed ... ``` -------------------------------- ### Basic Usage Example Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/input-basic.md Demonstrates how to use the InputBasic component with state management for the phone number digits. It configures the input for US national format. ```javascript import React, { useState } from 'react' import InputBasic from 'react-phone-number-input/input-core' function MyComponent() { const [phoneDigits, setPhoneDigits] = useState('') return ( ) } ``` -------------------------------- ### Ref Type Support Examples Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/use-external-ref.md Demonstrates how the hook supports various ref types including ref objects, callbacks, and combinations. ```javascript // Ref object const objectRef = useRef() ``` ```javascript // Callback console.log(instance)} /> ``` ```javascript // Combination (via wrapper) const handleRef = (el) => { objectRef.current = el props.externalRef?.(el) } ``` -------------------------------- ### Example: Dark Mode Customization Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/styling-and-customization.md Customize the appearance for dark mode by overriding CSS variables. This example shows how to change colors and borders for a dark theme. ```css :root.dark-mode { --PhoneInput-color: #fff; --PhoneInput-color--placeholder: #888; --PhoneInputCountryFlag-borderColor: #555; --PhoneInputCountrySelectArrow-color: #aaa; --PhoneInput-color--focus: #6699ff; --PhoneInput-border: 1px solid #555; } ``` -------------------------------- ### Core Metadata Usage Example Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/formatting-functions.md Shows how to import and use `libphonenumber-js` core metadata with the `formatPhoneNumber` function when using the core import path. ```javascript import metadata from 'libphonenumber-js/core' import { formatPhoneNumber } from 'react-phone-number-input/core' const formatted = formatPhoneNumber('+12133734253', 'NATIONAL', metadata) ``` -------------------------------- ### Get Countries with Different Metadata Variants Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/country-helpers.md Demonstrates how to import getCountries with different metadata configurations: default, minimal, and custom. ```javascript // With default metadata import { getCountries } from 'react-phone-number-input' // With minimal metadata import { getCountries } from 'react-phone-number-input/min' // With custom metadata import { getCountries } from 'react-phone-number-js/core' import metadata from 'libphonenumber-js/core' const countries = getCountries(metadata) ``` -------------------------------- ### Advanced React Hook Form Integration Example Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/react-hook-form-integration.md A comprehensive example demonstrating integration with React Hook Form, including form state management, default values, submission handling, and conditional error display. ```javascript import React from 'react' import { useForm, FormProvider, useFormContext } from 'react-hook-form' import PhoneInput from 'react-phone-number-input/react-hook-form' import 'react-phone-number-input/style.css' interface ContactForm { name: string phoneNumber: string email: string } function ContactFormComponent() { const methods = useForm({ defaultValues: { name: '', phoneNumber: '', email: '' } }) const onSubmit = (data: ContactForm) => { console.log('Submitted:', data) // data.phoneNumber is E.164 formatted } return (
{methods.formState.errors.phoneNumber && ( {methods.formState.errors.phoneNumber.message} )}
) } ``` -------------------------------- ### Real-World Phone Input and Formatting Example Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/formatting-functions.md This example demonstrates how to use the PhoneInput component and the formatPhoneNumber function within a React application to display phone numbers in national and international formats. ```javascript import React, { useState } from 'react' import PhoneInput, { formatPhoneNumber } from 'react-phone-number-input' import 'react-phone-number-input/style.css' function PhoneDisplay() { const [value, setValue] = useState('+12133734253') const displayNational = formatPhoneNumber(value) const displayIntl = formatPhoneNumber(value, 'INTERNATIONAL') return (

National format: {displayNational}

International format: {displayIntl}

) } ``` -------------------------------- ### Memoization Example in v3 Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/migration-guide.md Shows how components in v3 are automatically optimized with React.memo and useMemo, meaning props like `options` and `onChange` do not require manual memoization. ```javascript // Automatically optimized in v3 ``` -------------------------------- ### Basic Usage Example of usePhoneDigits Hook Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/use-phone-digits.md A practical example demonstrating how to integrate the usePhoneDigits hook into a React component. It shows state management for the phone number value and country, and how to bind the hook's output to an input field. ```javascript import React, { useState } from 'react' import usePhoneDigits from 'react-phone-number-input' function MyPhoneInput() { const [value, setValue] = useState() const [country, setCountry] = useState('US') const { phoneDigits, setPhoneDigits, inputFormat } = usePhoneDigits({ value, onChange: setValue, defaultCountry: country, metadata // Your metadata object }) return ( setPhoneDigits(e.target.value)} placeholder={getPlaceholder(inputFormat)} /> ) } ``` -------------------------------- ### React Native Phone Input Example Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/README.md A basic example of using the React Native phone input component. It requires state management for the phone number value and accepts a 'country' prop for initial country selection. ```javascript import React, { useState } from 'react' import PhoneInput from 'react-phone-number-input/react-native-input' function Example() { const [value, setValue] = useState() return ( ) } ``` -------------------------------- ### Import Default Styles Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/INDEX.md Import the default CSS styles for the phone number input component. This is the simplest way to get started with styling. ```javascript import 'react-phone-number-input/style.css' ``` -------------------------------- ### Dynamic Phone Input Configuration Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/website/index.html Example of dynamically changing phone input properties like labels and default country. Includes buttons to update these properties and demonstrate their effect. ```jsx this.setState({ dynamic_value: value })}/> this.setState({ dynamic_value: value })}/> this.setState({ dynamic_value: value })} initialValueFormat="national"/> ``` -------------------------------- ### CountrySelect Divider Option Example Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/country-select.md Shows how to use the 'divider' property to create visual separators within the CountrySelect dropdown options. ```javascript const options = [ { label: 'Frequently Used', divider: true }, { value: 'US', label: 'United States' }, { value: 'RU', label: 'Russia' }, { divider: true }, { value: 'FR', label: 'France' } ] ``` -------------------------------- ### Custom CSS for Flag Aspect Ratio Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/README.md Example of how to customize the aspect ratio for flag icons using CSS variables. ```css :root { --PhoneInputCountryFlag-aspectRatio: 1.333; } ``` -------------------------------- ### Flag Component Usage Example (URL-based) Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/flag.md Renders a flag using a default URL template. Ensure the `flagUrl` prop is correctly formatted with the country code placeholder. ```javascript import React from 'react' import Flag from 'react-phone-number-input' function MyComponent() { return ( ) } ``` -------------------------------- ### Example Usage of CountrySelect and PhoneInput Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/README.md Demonstrates how to integrate the CountrySelect component with the PhoneInput component for a complete phone number input form. Requires state management for country and phone number values. ```javascript import PhoneInput from 'react-phone-number-input/input' import en from 'react-phone-number-input/locale/en' import CountrySelect from './CountrySelect' function Example() { const [country, setCountry] = useState('US') const [value, setValue] = useState() return (
) } ``` -------------------------------- ### CountrySelectWithIcon Unicode Flags Example Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/country-select.md Demonstrates using the CountrySelectWithIcon component with the 'unicodeFlags' prop enabled to display emoji flags. ```javascript ``` -------------------------------- ### Phone Input with Internationalization (Russian Labels) Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/website/index.html Demonstrates how to internationalize the component by providing custom country names using the 'labels' prop. This example uses Russian labels. ```jsx import ru from 'react-phone-number-input/locale/ru' ``` -------------------------------- ### Unit Test for Phone Input Change Handling Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/migration-guide.md A unit test example using `@testing-library/react` to verify that the `onChange` handler is called correctly when the phone input value changes. ```javascript import { render, screen, fireEvent } from '@testing-library/react' import PhoneInput from 'react-phone-number-input' test('should handle phone input', () => { const onChange = jest.fn() render() const input = screen.getByRole('textbox') fireEvent.change(input, { target: { value: '+12133734253' } }) expect(onChange).toHaveBeenCalledWith('+12133734253') }) ``` -------------------------------- ### Translation File Structure Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/README.md This example shows the expected JSON structure for translation files used by the library. It includes common labels like 'country', 'phone', 'ext', and 'ZZ' for international, along with specific country codes and their names. ```js { "country": "Phone number country", "phone": "Phone", "ext": "ext.", // The rest are country names, including "unofficial" ones // like `AC`, `TA`, `XK`, and `ZZ` for "International". ..., "RO": "Romania", "RS": "Serbia", "RU": "Russia", ..., "ZZ": "International" } ``` -------------------------------- ### Basic React Hook Form Integration Example Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/README.md Demonstrates integrating both PhoneInput and PhoneInputWithCountry components into a react-hook-form. Ensure to pass the 'control' object from useForm() and define a 'name' for each input. ```javascript // "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 { // Either pass a `control` property to the component // or wrap it in a ``. control, handleSubmit } = useForm() return (
) } ``` -------------------------------- ### Phone Number Validation Example Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/README.md Shows how to use the `isPossiblePhoneNumber` function to validate a phone number input value. The result can be used with form validation frameworks. ```javascript import { isPossiblePhoneNumber } from 'react-phone-number-input' const isValid = (value) => Boolean(value) && isPossiblePhoneNumber(value) ``` -------------------------------- ### Common CDN URL Templates for Flags Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/flag.md Examples of URL templates for fetching flag images from various CDNs or custom hosts. The `{xx}` or `{XX}` placeholders are replaced with the country code. ```javascript // country-flag-icons (default) "https://cdn.jsdelivr.net/npm/country-flag-icons@1.5.0/react/2x1/{xx}.svg" ``` ```javascript // Alternative CDN "https://cdn.jsdelivr.net/npm/country-flag-icons@latest/react/2x1/{xx}.svg" ``` ```javascript // Custom hosted flags "https://mycdn.com/flags/{XX}.png" ``` ```javascript "https://mycdn.com/flags/{xx}.svg" ``` -------------------------------- ### Include Stylesheet without Webpack Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/README.md For projects not using Webpack, link the stylesheet in the HTML head. This is useful for static sites or simpler setups. ```html ``` -------------------------------- ### Custom Input Component with Inline Styles Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/styling-and-customization.md Replace the default input element with a custom component by passing it to the 'inputComponent' prop. This example shows a custom input with specific inline styles. ```javascript import PhoneInput from 'react-phone-number-input' function CustomInput(props) { return ( ) } ``` -------------------------------- ### Import Input-Only PhoneInput from /input-core Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/package-variants.md The '/input-core' variant provides an input-only phone number component with a small bundle size, excluding metadata. It requires you to pass the 'metadata' prop, making it ideal for minimal setups with custom country logic. ```javascript import PhoneInput from 'react-phone-number-input/input-core' ``` -------------------------------- ### Custom Input Component for InputSmart Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/input-smart.md Example of creating a custom input component that can be passed to InputSmart. This custom component sets the input type to 'tel' and input mode to 'numeric' for better mobile usability. ```javascript const CustomInputComponent = React.forwardRef((props, ref) => ( )) ``` -------------------------------- ### Get Current Phone Number Value Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/react-hook-form-integration.md Use the `watch` function from `useForm` to get the current value of the 'phoneNumber' field. The value is returned in E.164 format. ```javascript const { watch } = useForm() const phoneNumber = watch('phoneNumber') // phoneNumber is in E.164 format // Examples: "+12133734253", undefined, "" ``` -------------------------------- ### Import PhoneInput from /min Variant (Minimal Metadata) Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/package-variants.md The '/min' variant offers a medium bundle size by including only minimal metadata for major countries. Use this when your application primarily supports a limited set of countries and you want to reduce the overall package size. ```javascript import PhoneInput from 'react-phone-number-input/min' function App() { return } ``` -------------------------------- ### Metadata Parameter: v2 vs v3 (/core) Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/migration-guide.md Illustrates the requirement of the `metadata` prop when using the `/core` package variant in v3, which was sometimes optional in v2. ```javascript import PhoneInput from 'react-phone-number-input/core' ``` ```javascript import PhoneInput from 'react-phone-number-input/core' import metadata from 'libphonenumber-js/core' ``` -------------------------------- ### Get All Supported Countries Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/country-helpers.md Retrieves a list of all supported two-letter country codes. This function uses the default metadata. ```javascript import { getCountries } from 'react-phone-number-input' const allCountries = getCountries() // Returns: ['AC', 'AD', 'AE', 'AF', 'AG', ...] ``` -------------------------------- ### Importing Core Types from Main Package Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/types.md Demonstrates how to import essential types like Country, Value, and Labels from the main package. ```javascript import type { Country, Value, ExternalValue, Metadata, Labels, Flags, State, FeatureProps, Props } from 'react-phone-number-input' ``` -------------------------------- ### v3 Import Options Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/migration-guide.md In v3, you can choose different import paths based on your needs for metadata inclusion, affecting bundle size. ```javascript // Option 1: Same as v2 (includes all metadata) import PhoneInput from 'react-phone-number-input' ``` ```javascript // Option 2: Minimal metadata (saves ~70 KB) import PhoneInput from 'react-phone-number-input/min' ``` ```javascript // Option 3: Control metadata yourself (saves ~150 KB) import PhoneInput from 'react-phone-number-input/core' import metadata from 'libphonenumber-js/core' // Then pass metadata prop ``` -------------------------------- ### Get Country Calling Code Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/country-helpers.md Retrieves the international dialing prefix for a given two-letter country code. Requires metadata. ```javascript import { getCountryCallingCode } from 'react-phone-number-input' getCountryCallingCode('US', metadata) // "1" getCountryCallingCode('RU', metadata) // "7" getCountryCallingCode('GB', metadata) // "44" getCountryCallingCode('FR', metadata) // "33" getCountryCallingCode('JP', metadata) // "81" ``` -------------------------------- ### Optimized Imports for Bundle Size Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/migration-guide.md Demonstrates how to import only specific functions like `formatPhoneNumber` to reduce bundle size, as v3 offers better tree-shaking. ```javascript // Only imports needed components import { formatPhoneNumber } from 'react-phone-number-input' // Not imported: PhoneInput, flags, country utilities ``` -------------------------------- ### InputSmart Formatting Logic Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/input-smart.md Illustrates the core formatting logic within InputSmart, showing how it uses the AsYouType formatter to process input, generate display text, and determine template structure while managing prefixes. ```javascript const format = useCallback((value) => { const formatter = new AsYouType(country, metadata) const prefix = getPrefixForFormattingValueAsPhoneNumber({...}) // Format the number let text = formatter.input(prefix + value) let template = formatter.getTemplate() // Remove prefix from display if (prefix) { text = removePrefixFromFormattedPhoneNumber(text, prefix) if (template) { template = removePrefixFromFormattedPhoneNumber(template, prefix) } } return { text, // Formatted display text template // Template showing positions } }, [country, metadata]) ``` -------------------------------- ### Run Component Tests Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/README.md Execute the test suite for the component using npm. This command runs all defined tests. ```bash npm test ``` -------------------------------- ### React Hook Form Integration Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/README.md Integrate the PhoneInput component with React Hook Form for form management. Ensure 'react-hook-form' is installed. ```javascript import PhoneInput from 'react-phone-number-input/react-hook-form' import { useForm } from 'react-hook-form' function App() { const { control, handleSubmit } = useForm() return (
) } ``` -------------------------------- ### Import Default Package for All Countries Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/package-variants.md Use this import for a standard web application requiring support for all countries. Includes default styles. ```javascript import PhoneInput from 'react-phone-number-input' import 'react-phone-number-input/style.css' ``` -------------------------------- ### Get Country Calling Code Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/README.md Retrieves the country calling code for a given country code. Ensure the country code is supported. ```js import { getCountryCallingCode } from 'react-phone-number-input' getCountryCallingCode('US') === '1' ``` -------------------------------- ### Import PhoneInput from /core Variant (Requires Metadata) Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/package-variants.md Use the '/core' variant for a smaller bundle size when you want to manage metadata separately. This variant includes the PhoneInputWithCountry component and utility functions but requires you to provide the 'metadata' prop. ```javascript import PhoneInput from 'react-phone-number-input/core' import metadata from 'libphonenumber-js/core' function App() { return ( ) } ``` -------------------------------- ### Get Phone Number Validation Errors Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/react-hook-form-integration.md Access validation errors for the 'phoneNumber' field through `formState.errors`. Log the error message if it exists. ```javascript const { formState: { errors } } = useForm() if (errors.phoneNumber) { console.log(errors.phoneNumber.message) } ``` -------------------------------- ### Import Statements: v2 vs v3 Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/migration-guide.md Illustrates the change in import paths for custom input variants between v2 and v3. ```javascript import PhoneInput from 'react-phone-number-input' import PhoneNumberInput from 'react-phone-number-input/input' ``` ```javascript import PhoneInput from 'react-phone-number-input' // Same import PhoneInput from 'react-phone-number-input/input' // Changed name ``` -------------------------------- ### Phone Number Validation Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/website/index.html Utilize `isPossiblePhoneNumber()` to check if a phone number has a valid length. The example also shows how to check if a parsed number is possible. ```jsx this.setState({ value_validation: value })} />

{ this.state.value_validation ? ( libphonenumber.parsePhoneNumberFromString(this.state.value_validation) && libphonenumber.parsePhoneNumberFromString(this.state.value_validation).isPossible() ? '✅ Phone number length is correct' : '❌ Invalid phone number length' ) : ( You have not entered a phone number {/* Inserted an invisible UTF-8 emoji here to prevent `line-height` jumps. */} ) }

``` -------------------------------- ### Props Interface Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/input-basic.md Overview of the available props for the InputBasic component, their types, requirements, and descriptions. ```APIDOC ## Props Interface | Prop | Type | Required | Default | Description | |------|------|----------|---------|-------------| | value | `string` | Yes | — | Parsed phone digits (digits and optional leading '+' only). Examples: "", "+", "+123", "123". | | onChange | `(value: string) => void` | Yes | — | Callback when parsed value changes. Receives digits without formatting. | | onKeyDown | `(event: KeyboardEvent) => void | undefined` | No | — | Custom key down handler. Receives DOM keyboard events. | | country | `string | undefined` | No | — | Two-letter country code for national format. If not provided, formats as international. | | inputFormat | `'INTERNATIONAL' | 'NATIONAL_PART_OF_INTERNATIONAL' | 'NATIONAL' | 'INTERNATIONAL_OR_NATIONAL'` | Yes | — | Format mode for the input field. Determines how phone number is displayed and parsed. | | metadata | `Metadata` | No | — | `libphonenumber-js` metadata. If not provided, uses default metadata. | | inputComponent | `React.ElementType` | No | 'input' | Custom component for the actual input element. Receives all remaining props. | | international | `boolean` | No | false | Deprecated. No longer used, kept for backward compatibility. | | withCountryCallingCode | `boolean` | No | false | Deprecated. No longer used, kept for backward compatibility. | ``` -------------------------------- ### Importing PhoneInput Component Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/phone-input-with-country.md Shows different ways to import the PhoneInput component, including the default, a 'max' version, and a 'core' version requiring metadata. ```javascript import PhoneInput from 'react-phone-number-input' ``` ```javascript // or import PhoneInput from 'react-phone-number-input/max' ``` ```javascript // or with metadata required import PhoneInput from 'react-phone-number-input/core' ``` -------------------------------- ### Get Selected Option Helper Function Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/country-select.md Finds the option object that matches a given value from a list of options. Handles null or undefined values by defaulting to 'ZZ'. ```javascript function getSelectedOption(options, value) { return options.find(option => (option.value || 'ZZ') === (value || 'ZZ')) } ``` -------------------------------- ### Phone Input with Custom Country Order Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/website/index.html Demonstrates how to set a custom order for country options in the phone input component. ```html

countryOptionsOrder = ["US", "CA", "AU", "|", "..."]

this.setState({ countryOptionsOrder: value })} countryOptionsOrder={"[\"US\", \"CA\", \"AU\", \"|\", \"...\"]"}/> ``` -------------------------------- ### Min Import for Formatting Functions Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/formatting-functions.md Imports `formatPhoneNumber` and `formatPhoneNumberIntl` from the min path, which uses minimal metadata covering main countries and territories. ```javascript import { formatPhoneNumber, formatPhoneNumberIntl } from 'react-phone-number-input/min' ``` -------------------------------- ### Custom Country Select Component Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/styling-and-customization.md Replace the default country dropdown with a custom component using the 'countrySelectComponent' prop. This example demonstrates a custom select element for country selection. ```javascript import PhoneInput from 'react-phone-number-input' import { CountrySelect } from 'react-phone-number-input' function CustomCountrySelect(props) { const { value, onChange, options } = props return (
) } ``` -------------------------------- ### Flag Component Usage Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/flag.md This snippet demonstrates how to import and use the Flag component with its essential props. ```APIDOC ## Flag Component ### Description A component for rendering country flag icons. Supports both external image URLs and custom embedded flag components. ### Component Import ```javascript import Flag from 'react-phone-number-input' // or access via internal usage in PhoneInputWithCountry ``` ### Function Signature ```javascript function FlagComponent(props: FlagProps): React.JSX.Element ``` ### Props Interface | Prop | Type | Required | Description | |------|------|----------|-------------| | country | `Country` | Yes | Two-letter country code (ISO 3166-1 alpha-2). Examples: "US", "RU", "FR". | | countryName | `string` | Yes | Human-readable country name for HTML title attribute. Examples: "United States", "Russia", "France". | | flagUrl | `string` | Yes | Template URL for flag images. Placeholders replaced with country codes. Default: `https://cdn.jsdelivr.net/npm/country-flag-icons@1.5.0/react/2x1/{xx}.svg` | | flags | `Flags | undefined` | No | Object mapping country codes to React flag components. If provided and contains the country, uses embedded component instead of URL. | ### Behavior 1. **Check for embedded component**: If `flags[country]` exists, render it 2. **Fall back to image URL**: Otherwise, render `` with URL template 3. **Handle missing names**: Use empty string for role if countryName is missing ### Usage Examples #### Default URL-based Flags ```javascript import React from 'react' import Flag from 'react-phone-number-input' function MyComponent() { return ( ) } ``` Renders as: ```html United States ``` #### Embedded SVG Flags ```javascript import React from 'react' import Flag from 'react-phone-number-input' import flags from 'react-phone-number-input/flags' function MyComponent() { return ( ) } ``` With embedded flags, the flag component imported from the flags module is called: ```javascript flags.US({ title: 'United States' }) // Returns ... component ``` ### Flag URL Template The `flagUrl` parameter supports two placeholder patterns: | Placeholder | |-------------| | {XX} | Uppercase country code | | {xx} | Lowercase country code | ### Embedded Flags The `flags` prop accepts a `Flags` object (partial record of country codes to components): ```typescript type Flags = Partial> type EmbeddedFlag = (props: EmbeddedFlagProps) => React.JSX.Element type EmbeddedFlagProps = { title: string } ``` ### Using Embedded Flags ```javascript import flags from 'react-phone-number-input/flags' ``` ### Mixed Mode: Embedded + URL Fallback ```javascript import flags from 'react-phone-number-input/flags' function MyComponent() { const customFlags = { ...flags, // Override with custom component for specific country US: (props) =>
} return ( ) } ``` ### Accessibility #### Without Country Name ```javascript ``` Renders: ```html ``` #### With Country Name ```javascript ``` Renders: ```html United States ``` ### Styling The flag component is wrapped in a `
` for IE 11 compatibility with SVGs: ```javascript
...
``` ``` -------------------------------- ### Flags Type Definition with Example Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/types.md Defines a type for mapping country codes to embedded flag components. This allows for custom flag rendering by providing specific components for each country. ```typescript type Flags = Partial> ``` ```typescript const flags: Flags = { US: (props) => ..., RU: (props) => ..., FR: (props) => ... } ``` -------------------------------- ### API Reference Overview Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/MANIFEST.txt This section outlines the structure of the API reference documentation, detailing the available modules and their purposes. ```APIDOC ## API Reference Structure This API reference is organized hierarchically to provide comprehensive documentation for the `react-phone-number-input` library. ### Modules - **`phone-input-with-country.md`**: Documentation for the main phone input component with a country selector. - **`phone-input.md`**: Documentation for the core phone input component. - **`input-basic.md`**: Documentation for a basic input component. - **`input-smart.md`**: Documentation for a smart input component. - **`use-phone-digits.md`**: Documentation for the `usePhoneDigits` hook. - **`use-external-ref.md`**: Documentation for the `useExternalRef` hook. - **`country-select.md`**: Documentation for the country select component. - **`flag.md`**: Documentation for the flag component. - **`react-hook-form-integration.md`**: Documentation on integrating with React Hook Form. - **`formatting-functions.md`**: Documentation for phone number formatting utility functions. - **`country-helpers.md`**: Documentation for country-related helper functions. ### Documentation Details - **Props**: All component props are listed with their types, descriptions, and default values. - **Functions**: All exported functions are documented with signatures, parameter types, and return types. - **Types**: Type definitions for all exported types are provided, especially for TypeScript users. - **Examples**: Usage examples are provided for each major feature and integration scenario. - **Styling**: CSS classes and variables are listed for customization. - **Error Handling**: Documented error handling mechanisms. - **Browser Support**: Information on supported browsers. - **Package Variants**: Comparison of different package variants. - **Migration**: Guidance for migrating from v2 to v3. ``` -------------------------------- ### React Hook Form Integration Example Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/package-variants.md Integrate PhoneInput with react-hook-form by passing the 'control' object from useForm to the PhoneInput component. This enables automatic form state management and validation. ```javascript import PhoneInput from 'react-phone-number-input/react-hook-form' import { useForm } from 'react-hook-form' function App() { const { control, handleSubmit } = useForm() return (
) } ``` -------------------------------- ### Integration Test for Formatted Value Display Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/migration-guide.md An integration test example using `@testing-library/react` to check if the phone number is displayed in the correct formatted way after the component rerenders with a value. ```javascript test('should display formatted value', () => { const { rerender } = render( ) rerender( ) const input = screen.getByDisplayValue('(213) 373-4253') expect(input).toBeInTheDocument() }) ``` -------------------------------- ### Import TypeScript Types Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/INDEX.md Import all available TypeScript types for use in your project. Refer to types.md for a complete reference. ```typescript import type { Country, Value, ExternalValue, Metadata, Labels, Flags, State, Props, FeatureProps } from 'react-phone-number-input' ``` -------------------------------- ### Basic Usage of useExternalRef Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/use-external-ref.md Demonstrates how to use the useExternalRef hook to manage both internal and external refs for an input element. ```javascript import React, { useRef } from 'react' import useExternalRef from 'react-phone-number-input' function MyComponent(props) { const internalRef = useRef() const { refSetter, element } = useExternalRef(props.inputRef) // Use refSetter to set both internal and external refs const setRef = (el) => { internalRef.current = el refSetter(el) } return ( ) } ``` -------------------------------- ### Phone Number Input with Specific Country (US) Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/website/index.html Configures the input to only accept phone numbers in the national format for a specific country, using the `country` prop. Example shown for 'US'. ```jsx import Input from 'react-phone-number-input/input' ``` -------------------------------- ### Multi-Theme Support with CSS Variables Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/styling-and-customization.md Implement multi-theme support by conditionally applying CSS files or classes that define different theme variables. ```javascript import './light-theme.css' import './dark-theme.css' function App() { const [theme, setTheme] = useState('light') return (
) } ``` ```css .theme-light { --PhoneInput-color: #333; --PhoneInput-color--focus: #0066ff; } .theme-dark { --PhoneInput-color: #fff; --PhoneInput-color--focus: #66b3ff; } ``` -------------------------------- ### Setting Multiple Refs with setRefsValue Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/use-external-ref.md Shows how to use the setRefsValue utility function to set multiple refs simultaneously. ```javascript import { setRefsValue } from 'react-phone-number-input' // Set multiple refs at once setRefsValue([ref1, ref2, ref3], element) ``` ```javascript function setRefsValue(refs: (Ref | undefined)[], instance: any): void // Sets all refs in the array to the provided instance ``` -------------------------------- ### Locale Type Definition Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/types.md Represents a language locale identifier used for sorting country names and for translations. Examples include "en", "ru", and "fr". ```typescript type Locale = string ``` -------------------------------- ### Core Import for Formatting Functions Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/api-reference/formatting-functions.md Imports `formatPhoneNumber` and `formatPhoneNumberIntl` from the core path, requiring manual provision of metadata. ```javascript import { formatPhoneNumber, formatPhoneNumberIntl } from 'react-phone-number-input/core' ``` -------------------------------- ### Fixing 'Metadata is not defined' Error Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/migration-guide.md This code demonstrates the fix for the 'Metadata is not defined' error when using the `/core` variant by passing the metadata prop. ```javascript import PhoneInput from 'react-phone-number-input/core' import metadata from 'libphonenumber-js/core' ``` -------------------------------- ### Value Type Definition Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/types.md Defines a phone number in E.164 format, extending the E164Number type from libphonenumber-js. It represents a phone number as a string starting with '+' followed by the country calling code and the number. ```typescript type Value = E164Number ``` -------------------------------- ### Country Type Definition Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/types.md Defines a country code as a two-letter string adhering to the ISO 3166-1 alpha-2 standard. Examples include "US", "RU", and "FR". ```typescript type Country = CountryCode ``` -------------------------------- ### Import Minified Package for Major Countries Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/package-variants.md Choose this import when bundle size is a concern and support for only major countries is sufficient. Includes default styles. ```javascript import PhoneInput from 'react-phone-number-input/min' import 'react-phone-number-input/style.css' ``` -------------------------------- ### Custom Country Filtering Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/_autodocs/INDEX.md Illustrates how to filter the list of available countries in the phone input component. This example restricts the selection to North American countries (US, CA, MX) and sets the default country to US. ```javascript ``` -------------------------------- ### Get Country Names in Russian Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/README.md This snippet demonstrates how to import and process country names from a JSON file for a specific language (Russian in this case). It sorts the country codes and creates a new object with country names. ```js import countryNamesInRussian from 'country-list/data/ru/country.json' // Outputs a JSON with the country names. JSON.stringify( Object.keys(countryNamesInRussian).sort() .reduce((all, country) => ({ ...all, [country]: countries[country] }), {}), null, ' ' ) ``` -------------------------------- ### Generate Code Coverage Report Source: https://github.com/catamphetamine/react-phone-number-input/blob/master/README.md Generate a detailed code coverage report for the component's core source files. The report can be viewed in a web browser. ```bash npm run test-coverage ```