### Quick Start Example Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/00_START_HERE.txt A basic example demonstrating how to use the PhoneInput component with common configurations like country selection, search, area codes, and custom validation. ```javascript import PhoneInput from 'react-phone-input-2' import 'react-phone-input-2/lib/style.css' setPhone(phone)} enableSearch={true} enableAreaCodes={['us', 'ca']} isValid={(value, country) => { if (country.iso2 === 'us') { return value.replace(/\D/g, '').length === 10 } return true }} /> ``` -------------------------------- ### Install React-Phone-Input-2 Source: https://github.com/bl00mber/react-phone-input-2/blob/master/README.md Install the library using npm. This command adds the package as a project dependency. ```shell-script npm install react-phone-input-2 --save ``` -------------------------------- ### Handle Form Submission Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/quick-reference.md Example of how to retrieve the phone number and country data upon form submission using a ref. ```jsx const handleSubmit = () => { const data = phoneRef.current.getCountryData(); console.log(`Phone: ${phone}, Country: ${data.countryCode}`); }; ``` -------------------------------- ### Basic Phone Input Configuration Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/configuration.md Demonstrates the fundamental setup for react-phone-input-2, including importing the component and its styles, and handling basic input changes. ```jsx import PhoneInput from 'react-phone-input-2'; import 'react-phone-input-2/lib/style.css'; setPhone(phone)} /> ``` -------------------------------- ### State Batching Example Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/StateManagement.md Demonstrates how React batches multiple setState() calls within a single event handler into one re-render for efficiency. ```javascript handleFlagItemClick = (country, e) => { // All these calls batch into one re-render this.setState({ showDropdown: false }) this.setState({ selectedCountry: newSelectedCountry }) this.setState({ formattedNumber }) // Single re-render after all three } ``` -------------------------------- ### Example Raw Country Entries Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/RawData.md Illustrates sample entries from the raw country data array, showcasing different combinations of provided fields. ```javascript [ 'United States', ['north-america'], 'us', '1', '(...) ...-....', 0, ['202', '212', '415', '516', ...] // ~400 area codes for US ] ``` ```javascript [ 'United Kingdom', ['europe', 'eu-union'], 'gb', '44', '.... ... .....' // No priority or areaCodes ] ``` ```javascript [ 'France', ['europe', 'eu-union'], 'fr', '33', '.. .. .. .. ..', 1 // No areaCodes ] ``` -------------------------------- ### Example Usage of Phone Input Event Callbacks Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/types.md Demonstrates how to implement and pass event handler functions to the PhoneInput component for onChange, isValid, and onEnterKeyPress. ```typescript const handleChange = ( value: string, data: CountryData | {}, event: React.ChangeEvent, formattedValue: string ) => { console.log('Unformatted:', value); // e.g., '2025551234' console.log('Formatted:', formattedValue); // e.g., '+1 (202) 555-1234' console.log('Country:', data); // CountryData object }; const validatePhone = ( value: string, country: object, countries: object[], hiddenAreaCodes: object[] ): boolean | string => { if (value.match(/12345/)) { return 'Invalid number: ' + value; } return value.length >= 10; }; console.log('Enter pressed')} /> ``` -------------------------------- ### Configure Long Number Limits Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/InputHandling.md Examples of how to configure the 'enableLongNumbers' prop to control the maximum digit limit for phone numbers. ```jsx // No limit // Max 20 digits // Enforce 15 (default) ``` -------------------------------- ### Using Spanish Localization Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/configuration.md Import and apply a specific language JSON file to localize the phone input component. This example demonstrates using the Spanish language file. ```jsx import PhoneInput from 'react-phone-input-2'; import es from 'react-phone-input-2/lang/es.json'; ``` -------------------------------- ### Derived Data Examples Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/StateManagement.md Illustrates values computed on-the-fly without explicit state storage. These are derived from existing state or computed during the render cycle. ```javascript // Derived from state const inputClasses = classNames({ 'invalid-number': !isValidValue, 'open': showDropdown }) ``` ```javascript // Computed during render const searchedCountries = this.getSearchFilteredCountries() ``` ```javascript // Memoized functions for performance getProbableCandidate = memoize((queryString) => { ... }) ``` ```javascript guessSelectedCountry = memoize((inputNumber, ...) => { ... }) ``` -------------------------------- ### Common Phone Number Patterns by Country Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/Formatting.md Provides examples of common phone number format patterns for various countries, illustrating country codes and their corresponding formats. ```Markdown | Country | Code | Pattern | Example | |---------|------|---------|---------| | United States | us | `(...) ...-....` | `(202) 555-1234` | | Canada | ca | `(...) ...-....` | `(416) 555-1234` | | United Kingdom | gb | `.... ... .....` | `2071 946 0958` | | France | fr | `.. .. .. .. ..` | `12 34 56 78 90` | | Germany | de | `... ......` | `123 456789` | | Japan | jp | `.... .... ....` | `0120 1234 5678` | | Australia | au | `.... ... ...` | `2071 946 0958` | ``` -------------------------------- ### Style Interface Usage Example Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/types.md Illustrates how to apply custom styles using the Style interface. These properties are passed directly to the corresponding DOM elements for customization. ```typescript const style: Style = { containerClass: 'phone-input-wrapper', inputClass: 'phone-input-field', containerStyle: { border: '1px solid blue', padding: '10px' }, inputStyle: { fontSize: '16px', minHeight: '40px' } }; ``` -------------------------------- ### Controlled Component Example Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/INDEX.md Use this snippet to manage the phone input's value using React state for a controlled component. ```jsx const { useState } = require('react'); const PhoneInput = require('react-phone-input-2').default; function Example() { const [phone, setPhone] = useState(''); return setPhone(v)} />; } ``` -------------------------------- ### PhoneInputProps Interface Example Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/types.md Demonstrates how to configure the PhoneInput component using the PhoneInputProps interface. This includes setting default country, input value, enabling features like area code search, and localizing country names. ```typescript const props: PhoneInputProps = { country: 'us', value: '2025551234', enableAreaCodes: ['us', 'ca'], enableSearch: true, regions: 'north-america', onlyCountries: ['us', 'ca', 'mx'], preferredCountries: ['us', 'ca'], masks: { us: '+1 (...) ...-....', ca: '+1 (...) ...-....' }, localization: { us: 'USA', ca: 'Canada', mx: 'Mexico' }, placeholder: 'Enter phone number', searchPlaceholder: 'Find country', onChange: (value, data) => console.log(value, data), containerClass: 'my-phone-input', inputStyle: { fontSize: '16px' } }; ``` -------------------------------- ### Raw Country Entry Example Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/RawData.md Illustrates the structure of a single raw country entry before processing. This format includes name, regions, ISO code, dial code, mask, priority, and area codes. ```javascript [ 'United States', ['north-america'], 'us', '1', '(...) ...-....', 0 ] ``` -------------------------------- ### Conditional Logic Based on Dropdown Visibility Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/StateManagement.md An example demonstrating how to conditionally execute code based on the `showDropdown` state property. This is useful for controlling UI elements or logic when the country selection dropdown is open. ```javascript if (this.state.showDropdown) { // Dropdown is open } ``` -------------------------------- ### Accessing PhoneInput Component Methods Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/quick-reference.md Utilize a ref to access methods like getting country data, formatting numbers, and guessing the selected country. ```javascript const phoneRef = useRef(); // Get country data phoneRef.current.getCountryData() // Format a number phoneRef.current.formatNumber('2025551234', countryData) // Guess country from number phoneRef.current.guessSelectedCountry('442071946000', 'us', countries, hidden) ``` -------------------------------- ### PhoneInput Usage Example Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/PhoneInput.md Demonstrates how to use the PhoneInput component in a React form. It includes state management for the phone number, handling country data changes, and retrieving country information on form submission. ```javascript import React, { useRef, useState } from 'react'; import PhoneInput from 'react-phone-input-2'; import 'react-phone-input-2/lib/style.css'; export function MyPhoneForm() { const [phone, setPhone] = useState(''); const phoneRef = useRef(); const handleChange = (value, countryData, event, formattedValue) => { setPhone(value); console.log('Country:', countryData); }; const handleSubmit = () => { const country = phoneRef.current.getCountryData(); console.log('Submitting phone:', phone, 'Country:', country); }; return ( <> ); } ``` -------------------------------- ### Get Probable Candidate Method Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/PhoneInput.md A memoized function to find a country that matches the beginning of a country name. This is used for keyboard-based country searches. ```javascript getProbableCandidate(queryString: string): CountryObject | null ``` -------------------------------- ### Format US Phone Number Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/Formatting.md Example of formatting a US phone number using a predefined country object with the `formatNumber` function. ```javascript const country = { iso2: 'us', format: '(...) ...-....', ... } const formatted = formatNumber('2025551234', country) // Result: '+1 (202) 555-1234' ``` -------------------------------- ### CountryData Interface Usage Example Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/types.md Demonstrates how to use the CountryData interface for type checking and in a callback function. The country parameter in event handlers conforms to this structure. ```typescript const countryData: CountryData = { name: 'United States', dialCode: '+1', countryCode: 'us', format: '+. (...) ...-....' }; function handleChange(value: string, country: CountryData) { console.log(`Phone: ${value} from ${country.name}`); } ``` -------------------------------- ### Get Element Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/PhoneInput.md Retrieves a specific DOM element for a country list item based on its index. It uses a ref named `flag_no_${index}` to find the element. ```javascript getElement(index: number): HTMLElement | undefined ``` -------------------------------- ### Get Country Dropdown List Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/PhoneInput.md Renders the entire country selection dropdown list. This includes the optional search input, country items, preferred countries separator, and a 'no results' message if applicable. ```javascript getCountryDropdownList(): React.ReactNode ``` -------------------------------- ### Validate Phone Number with Country Dial Codes Source: https://github.com/bl00mber/react-phone-input-2/blob/master/README.md This example uses lodash.startswith to validate if the input number starts with any of the country's dial codes. ```javascript import startsWith from 'lodash.startswith'; { return countries.some((country) => { return startsWith(inputNumber, country.dialCode) || startsWith(country.dialCode, inputNumber); }); }} /> ``` -------------------------------- ### Instantiate CountryData with Custom Options Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/CountryData.md Demonstrates how to create a new CountryData instance with various configuration options, including regions, country filtering, masks, and localization. Use this to customize country data behavior for specific applications. ```javascript import CountryData from './CountryData'; const countryData = new CountryData( true, // enableAreaCodes false, // enableTerritories 'europe', // regions ['fr', 'de', 'it', 'es'], // onlyCountries ['de', 'fr'], // preferredCountries [], // excludeCountries ['onlyCountries'], // preserveOrder { fr: '(...) ..-..-..', at: '(....) ...-....' }, // masks null, // priority { gr: ['2694', '2647'], fr: ['369', '463'] }, // areaCodes { de: 'Deutschland', fr: 'France' }, // localization '+', // prefix '... ... ... ... ..', // defaultMask false // alwaysDefaultMask ); console.log(countryData.onlyCountries); // Filtered and sorted countries console.log(countryData.preferredCountries); // Countries to show first console.log(countryData.hiddenAreaCodes); // Area codes for detection ``` -------------------------------- ### Format US Phone Number with Custom Mask Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/Formatting.md Example of formatting a US phone number using a custom mask with spaces as separators. ```javascript const country = { iso2: 'us', format: '+1 ... ... ....' } const formatted = formatNumber('2025551234', country) // Result: '+1 202 555 1234' (spaces instead of parens and hyphens) ``` -------------------------------- ### Importing React Phone Input 2 Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/RawData.md Demonstrates how to import the library in both ES modules and CommonJS environments. Use the ES module import for modern bundlers and the CommonJS script tag for CDN usage. ```javascript // ES modules import PhoneInput from 'react-phone-input-2'; ``` ```javascript // CommonJS (CDN) ``` -------------------------------- ### Include react-phone-input-2 via CDN Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/quick-reference.md Include the library script from a CDN and access the PhoneInput component. ```html ``` -------------------------------- ### Import and Log Raw Countries Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/RawData.md Import the raw countries data and iterate through it to log country names and ISO codes. This is useful for inspecting the available country data. ```javascript import rawCountries from 'react-phone-input-2/lib/rawCountries'; rawCountries.forEach(country => { const [name, regions, iso2, dialCode, mask, priority, areaCodes] = country; console.log(`${name} (${iso2}): +${dialCode}`); }); ``` -------------------------------- ### Constructor Logic for State Initialization Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/StateManagement.md Initializes the component's state by processing props, determining the initial country based on various factors, formatting the number, and finding the highlight index for the country list. ```javascript constructor(props) { // 1. Create CountryData instance with all filters applied const { onlyCountries, preferredCountries, hiddenAreaCodes } = new CountryData(...) // 2. Extract digits from initial value const inputNumber = props.value ? props.value.replace(/\D/g, '') : '' // 3. Determine initial country (in priority order) let countryGuess if (props.disableInitialCountryGuess) { countryGuess = 0 } else if (inputNumber.length > 1) { // Detect from phone number countryGuess = this.guessSelectedCountry(...) } else if (props.country) { // Use provided country countryGuess = onlyCountries.find(o => o.iso2 == props.country) } else { // No country countryGuess = 0 } // 4. Format initial number let formattedNumber = ...this.formatNumber(...) // 5. Find highlight index const highlightCountryIndex = onlyCountries.findIndex(o => o == countryGuess) // 6. Initialize state this.state = { ... } } ``` -------------------------------- ### Country Name Property Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/RawData.md Specifies the English name of the country as it will be displayed in dropdown menus. Example values include 'United States', 'United Kingdom', and 'Germany'. ```javascript type: string example: 'United States', 'United Kingdom', 'Germany' ``` -------------------------------- ### Custom Validation Logic Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/quick-reference.md Implement custom validation logic for the phone number based on the selected country. This example checks for 10 digits for US numbers. ```jsx isValid={(value, country) => { if (country.iso2 === 'us') { return value.replace(/\D/g, '').length === 10; } return true; }} ``` -------------------------------- ### PhoneInput File Structure Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/INDEX.md Details the organization of directories and key files within the react-phone-input-2 project. ```markdown react-phone-input-2/ ├── src/ │ ├── index.js (1015 lines) — Main PhoneInput component │ ├── CountryData.js (241 lines) — Country data processing │ ├── rawCountries.js (1362 lines) — Country data array │ ├── rawTerritories.js (171 lines) — Territory data array │ └── utils/ │ └── prototypes.js — String.prototype polyfills ├── lib/ — Built output │ ├── lib.js — UMD bundle │ ├── style.css — Default CSS theme │ ├── material.css — Material Design theme │ ├── bootstrap.css — Bootstrap theme │ └── ... (other themes) ├── lang/ — Language files │ ├── es.json — Spanish │ ├── de.json — German │ └── ... (12 more languages) ├── test/ — Test files ├── index.d.ts — TypeScript definitions ├── package.json — NPM metadata └── README.md — Usage documentation ``` -------------------------------- ### TypeScript Usage with PhoneInput Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/INDEX.md Demonstrates how to import and use the PhoneInput component with TypeScript, including handling value changes and accessing country data. Ensure you have the necessary types imported. ```typescript import PhoneInput from 'react-phone-input-2'; import type { PhoneInputProps, CountryData } from 'react-phone-input-2'; const handleChange = (value: string, data: CountryData) => { // value: unformatted digits (e.g., '2025551234') // data: { name, dialCode, countryCode, format } }; ``` -------------------------------- ### Use Pre-built Spanish Localization Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/quick-reference.md Import and apply a pre-built localization JSON file for Spanish. This allows the component to display labels and country names in Spanish. ```jsx import es from 'react-phone-input-2/lang/es.json'; ``` -------------------------------- ### Get Dropdown Country Name Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/PhoneInput.md Determines the display name for a country within the dropdown list. It prioritizes the `localName` if available, otherwise falls back to the `name` property. ```javascript getDropdownCountryName(country: CountryObject): string ``` -------------------------------- ### User-Driven State Updates with setState Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/StateManagement.md Demonstrates how to update component state in response to user interactions using `this.setState()`. Includes a simple toggle and a batched update with a callback. ```javascript // Simple state update this.setState({ showDropdown: !this.state.showDropdown }) ``` ```javascript // Batched update with callback this.setState({ formattedNumber, selectedCountry: newSelectedCountry, freezeSelection: true }, () => { // Callback after state update completes this.cursorToEnd() }) ``` -------------------------------- ### Get Country Data Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/PhoneInput.md Retrieves the data object for the currently selected country. Useful for accessing details like the country name, dial code, ISO code, and format mask. ```javascript const countryData = phoneInputRef.getCountryData(); console.log(countryData); // { name: 'United States', dialCode: '1', countryCode: 'us', format: '+. (...) ...-....' } ``` -------------------------------- ### initUserContent Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/CountryData.md Merges user-provided custom masks, priorities, and area codes into a normalized structure for extension. ```APIDOC ## initUserContent ### Description Merges user-provided custom masks, priorities, and area codes into a normalized structure for extension. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **masks** (object) - Required - User-defined custom masks - **priority** (object) - Required - User-defined priority settings - **areaCodes** (object) - Required - User-defined area codes ### Request Example ```javascript initUserContent(customMasks, prioritySettings, areaCodeData) ``` ### Response #### Success Response (200) - **array** - Normalized structure for user content extension. #### Response Example ```json [ { "countryCode": "US", "masks": [ "(...) ...-...." ] } ] ``` ``` -------------------------------- ### Get Country Format Mask Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/CountryData.md Constructs the complete format mask for a country. It prioritizes predefined masks unless `alwaysDefaultMask` is true or no predefined mask is provided, in which case it uses the default mask. ```javascript function getMask(prefix: string, dialCode: string, predefinedMask: string, defaultMask: string, alwaysDefaultMask: boolean): string ``` -------------------------------- ### Import Material Style Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/quick-reference.md Import the material design stylesheet for the phone input component. This should be done once in your application. ```jsx import 'react-phone-input-2/lib/material.css' ``` -------------------------------- ### Get Search Filtered Countries Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/PhoneInput.md Filters the list of countries based on the current search value. It searches across dial codes, ISO2 codes, and country names, including localized names. ```javascript getSearchFilteredCountries(): CountryObject[] ``` -------------------------------- ### PhoneInput Constructor Signature Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/PhoneInput.md Shows the constructor signature for the PhoneInput component, accepting PhoneInputProps. ```javascript constructor(props: PhoneInputProps) ``` -------------------------------- ### handleKeydown (Global) Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/InputHandling.md Handles keyboard navigation and interactions within the dropdown list and input field. It supports arrow keys for navigation, ENTER to select, ESC/TAB to close, and A-Z/SPACE for searching countries. ```APIDOC ## handleKeydown (Global) ### Description Handles keyboard navigation in the dropdown and input. Supports arrow keys, ENTER, ESC, TAB, and character search. ### Method ```javascript void handleKeydown(e: React.KeyboardEvent) ``` ### Key Handlers - **UP/DOWN arrows**: Navigate country list highlight. - **ENTER**: Select highlighted country. - **ESC**: Close dropdown. - **TAB**: Close dropdown. - **A-Z, SPACE**: Start country name search (debounced). ### Usage Example ```javascript handleKeydown = (e) => { const { keys } = this.props; if (className.includes('selected-flag') && e.which === keys.ENTER) { return this.handleFlagDropdownClick(e); } if (className.includes('form-control') && (e.which === keys.ENTER || e.which === keys.ESC)) { return e.target.blur(); } if (!this.state.showDropdown || this.props.disabled) return; if (className.includes('search-box')) { if (e.which !== keys.UP && e.which !== keys.DOWN && e.which !== keys.ENTER) { if (e.which === keys.ESC && e.target.value === '') { // Close dropdown if search is empty } else { return; // Don't process other events in search field } } } const moveHighlight = (direction) => { this.setState({ highlightCountryIndex: this.getHighlightCountryIndex(direction) }, () => { this.scrollTo(this.getElement(this.state.highlightCountryIndex), true); }); }; switch (e.which) { case keys.DOWN: moveHighlight(1); break; case keys.UP: moveHighlight(-1); break; case keys.ENTER: this.handleFlagItemClick( this.getSearchFilteredCountries()[this.state.highlightCountryIndex], e ); break; case keys.ESC: case keys.TAB: this.setState({ showDropdown: false }, this.cursorToEnd); break; default: if ((e.which >= keys.A && e.which <= keys.Z) || e.which === keys.SPACE) { this.setState({ queryString: this.state.queryString + String.fromCharCode(e.which) }, this.state.debouncedQueryStingSearcher); } } } ``` ``` -------------------------------- ### ISO2 Code Property Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/RawData.md Represents the ISO 3166-1 alpha-2 country code, which is a unique two-character identifier used for country filtering and lookup. Examples include 'us', 'gb', 'fr', 'de', 'au'. ```javascript type: string example: 'us', 'gb', 'fr', 'de', 'au' length: 2 characters ``` -------------------------------- ### Import Component and Styles Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/quick-reference.md Import the PhoneInput component and its default CSS styles. Ensure these are imported once in your application. ```javascript import PhoneInput from 'react-phone-input-2'; import 'react-phone-input-2/lib/style.css'; ``` -------------------------------- ### Dial Code Property Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/RawData.md The international telephone dialing code for a country, provided as a string without the '+' prefix. This is used for phone number detection and formatting. Examples are '1', '44', '33', '49', '61'. ```javascript type: string example: '1', '44', '33', '49', '61' ``` -------------------------------- ### Customize Search Placeholder and Not Found Message Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/Dropdown.md Use `searchPlaceholder` to set the text displayed in an empty search field and `searchNotFound` to specify the message shown when no countries match the search query. ```jsx ``` -------------------------------- ### Event Callbacks for PhoneInput Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/INDEX.md Lists the available event callbacks for the PhoneInput component and their parameters. Note that onKeyDown does not receive country data. ```javascript onChange(value, country, event, formattedValue) // On phone/country change onFocus(event, country) // On input focus onBlur(event, country) // On input blur onClick(event, country) // On input click onKeyDown(event) // On any key (NO country data) onEnterKeyPress(event) // On ENTER key specifically onMount(value, country, formattedValue) // After mount isValid(value, country, countries, hiddenAreaCodes) // Validation function ``` -------------------------------- ### render Method Signature Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/PhoneInput.md Returns the complete JSX structure for the PhoneInput component. This includes the input field, country selection button, and the dropdown list, with CSS classes applied based on component state and props. ```javascript render(): React.ReactNode ``` -------------------------------- ### PhoneInput Component Hierarchy Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/INDEX.md Illustrates the nested structure of the PhoneInput component and its sub-elements. ```markdown PhoneInput (React.Component) ├── Input Field ( ├── Flag/Country Button (
└── Dropdown List (
    ├── Search Field (optional) ├── Country Items (
  • x N) └── Divider (between preferred & others) ``` -------------------------------- ### Import and Log Raw Territories Count Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/RawData.md Import the raw territories data and log its length to understand the total number of territories available. This can be used for data validation or reporting. ```javascript import rawTerritories from 'react-phone-input-2/lib/rawTerritories'; console.log(rawTerritories.length); // Number of territories ``` -------------------------------- ### Import Predefined Localization Data Source: https://github.com/bl00mber/react-phone-input-2/blob/master/README.md Import JSON files for predefined localizations to support different languages. This allows the component to display country names and other text in the user's preferred language. ```jsx import es from 'react-phone-input-2/lang/es.json' ``` -------------------------------- ### Initialize User Content Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/CountryData.md Merges user-provided custom masks, priorities, and area codes into a normalized structure for use in extending country data. ```javascript function initUserContent(masks: object, priority: object, areaCodes: object): array ``` -------------------------------- ### Key Code Constants Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/InputHandling.md Defines static default properties for key code constants used throughout the component for keyboard event handling. ```APIDOC ## Key Code Constants ### Description Provides default key code constants for common keyboard events. ### Static Default Properties ```javascript static defaultProps = { keys: { UP: 38, DOWN: 40, RIGHT: 39, LEFT: 37, ENTER: 13, ESC: 27, PLUS: 43, A: 65, Z: 90, SPACE: 32, TAB: 9 } } ``` ``` -------------------------------- ### Handle Input Method Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/PhoneInput.md The primary handler for input changes. It formats the input, detects the country, manages the caret position, and triggers the `onChange` callback. It validates input length, auto-detects country, applies formatting, preserves caret position, and fires `onChange` with detailed data. ```javascript handleInput(e: React.ChangeEvent): void ``` -------------------------------- ### Importing Material Design CSS Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/configuration.md Import the Material Design CSS file to apply the Material styling to the phone input component. Ensure this import is placed alongside the component import. ```jsx import PhoneInput from 'react-phone-input-2'; import 'react-phone-input-2/lib/material.css'; // Material styling ``` -------------------------------- ### getMask Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/CountryData.md Constructs the complete format mask for a country. It uses the default mask if no predefined mask is provided or if `alwaysDefaultMask` is true; otherwise, it uses the predefined mask. ```APIDOC ## getMask ### Description Constructs the complete format mask for a country. If no predefined mask or `alwaysDefaultMask` is true, uses the default mask; otherwise uses the predefined mask. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **prefix** (string) - Required - Phone prefix (e.g., '+') - **dialCode** (string) - Required - Country dial code (e.g., '1') - **predefinedMask** (string) - Required - Country-specific format mask - **defaultMask** (string) - Required - Fallback mask to use if no predefined mask - **alwaysDefaultMask** (boolean) - Required - If true, ignores predefinedMask ### Request Example ```javascript getMask('+', '1', '(...) ...-....', '. ... ...-....', false) ``` ### Response #### Success Response (200) - **mask** (string) - Complete format mask string (e.g., '+. (...) ...-....') #### Response Example ```json { "mask": "+1 (...) ...-...." } ``` ``` -------------------------------- ### handleInputKeyDown Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/InputHandling.md Handles key presses on the main input field. It can trigger an `onEnterKeyPress` callback when the ENTER key is pressed and always fires an `onKeyDown` callback for any key press. ```APIDOC ## handleInputKeyDown ### Description Handles key presses on the input field. Fires `onEnterKeyPress` for the ENTER key and `onKeyDown` for any key. ### Method ```javascript void handleInputKeyDown(e: React.KeyboardEvent) ``` ### Parameters None directly exposed in the callback, but it uses `this.props.keys` and callbacks like `onEnterKeyPress` and `onKeyDown`. ### Usage Example ```javascript handleInputKeyDown = (e) => { const { keys, onEnterKeyPress, onKeyDown } = this.props; if (e.which === keys.ENTER) { if (onEnterKeyPress) onEnterKeyPress(e); } if (onKeyDown) onKeyDown(e); } ``` **Note:** This handler does NOT receive country data in the callback. ``` -------------------------------- ### Search and UI Options for Phone Input Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/quick-reference.md Control the visibility of the search box and country selector, set the initial dropdown state, use custom flags, and set a special label for the input. ```jsx ``` -------------------------------- ### Handle Double Click to Select All Text Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/InputHandling.md Selects all text within the input field upon a double-click event. ```javascript handleDoubleClick = (e) => { const len = e.target.value.length; e.target.setSelectionRange(0, len); } ``` -------------------------------- ### onChange Callback Parameters Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/InputHandling.md The `onChange` callback is invoked after formatting and state updates, providing detailed information about the input. Use these parameters to access the unformatted digits, country data, original event, and the fully formatted string. ```javascript if (onChange) onChange( formattedNumber.replace(/[^0-9]+/g, ''), // Unformatted digits only this.getCountryData(), // Country object e, // Original event formattedNumber // Formatted with all chars ); ``` -------------------------------- ### Handle Search Input Change Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/Dropdown.md The `handleSearchChange` method updates the component's state with the user's search input. It also handles resetting the highlighted country when the search input is cleared. ```javascript handleSearchChange(e: React.ChangeEvent): void ``` ```javascript handleSearchChange = (e) => { const { currentTarget: { value: searchValue } } = e; const { preferredCountries, selectedCountry } = this.state; let highlightCountryIndex = 0; if (searchValue === '' && selectedCountry) { // When search is cleared, highlight the selected country const { onlyCountries } = this.state; highlightCountryIndex = this.concatPreferredCountries( preferredCountries, onlyCountries ).findIndex(o => o == selectedCountry); setTimeout(() => this.scrollTo(this.getElement(highlightCountryIndex)), 100); } this.setState({ searchValue, highlightCountryIndex }); } ``` -------------------------------- ### Apply Custom Class and Styles to Search Input Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/Dropdown.md Use `searchClass` to apply a custom CSS class to the search input wrapper and `searchStyle` for inline styles. ```jsx ``` -------------------------------- ### getHighlightCountryIndex Method Signature Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/PhoneInput.md Calculates the next highlight index for country selection based on direction. It ensures the index stays within the valid range. ```javascript getHighlightCountryIndex(direction: number): number ``` -------------------------------- ### Dropdown Navigation with Arrow Keys Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/Dropdown.md Handles UP/DOWN arrow key presses to move the highlight between countries in the dropdown. ```javascript case keys.DOWN: moveHighlight(1); // Move down break; case keys.UP: moveHighlight(-1); // Move up break; ``` -------------------------------- ### State Persistence Explanation Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/StateManagement.md Explains that state persists across re-renders unless explicitly changed. This is crucial for maintaining user input and selections. ```javascript // User types several digits, selects country, types more // State.selectedCountry persists through all keystroke re-renders // unless guessSelectedCountry() changes it // Closing dropdown keeps selectedCountry unchanged // Re-opening dropdown highlights the same country ``` -------------------------------- ### getCountryDropdownList Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/Dropdown.md Renders the complete dropdown UI, including the search field and the country list. It returns a `
      ` element representing the dropdown. ```APIDOC ## getCountryDropdownList ### Description Renders the complete dropdown UI including search field and country list. ### Method ```javascript getCountryDropdownList(): React.ReactNode ``` ### Returns Returns a `
        ` element with the following structure: ```jsx
          {enableSearch && (
        • )}
        • ...
        • ...
        • ...
        • No entries to show
        ``` ### Preferred Countries Separator If preferred countries are configured, a visual divider is inserted after them. This divider is only shown when search is empty or disabled. ```javascript const dashedLi = (
      • ); (preferredCountries.length > 0) && (!enableSearch || enableSearch && !searchValue.trim()) && countryDropdownList.splice(preferredCountries.length, 0, dashedLi); ``` ### Country List Items Each country renders as an `
      • ` element with specific attributes. ```jsx
      • this.handleFlagItemClick(country, e)} tabIndex={disableDropdown ? '-1' : '0'} role="option" aria-selected={highlight ? true : undefined} >
        Germany +49
      • ``` **Attributes:** - `className="country"` — Base class - `className="highlight"` — Added when highlighted - `className="preferred"` — Added for US and GB (hardcoded; see note) - `className="active"` — Added for US (hardcoded; see note) - `data-flag-key="flag_no_${index}"` — Used for ref - `data-dial-code='1'` — Always '1' (hardcoded; see note) - `data-country-code={country.iso2}` — Country code **Notes:** Some properties are hardcoded as 'us' or 'gb' and should not be relied upon. ``` -------------------------------- ### Form Integration with Event Handlers Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/configuration.md Integrates the phone input into a form, managing form data updates, focus/blur events, submission, and input validation. ```jsx { setFormData({ ...formData, phone: value, country: data.countryCode }); }} onFocus={() => setFieldFocused('phone')} onBlur={() => setFieldFocused(null)} onEnterKeyPress={() => submitForm()} inputProps={{ name: 'phone', id: 'phone-input', required: true, autoFocus: true }} placeholder="Enter your phone number" isValid={isPhoneValid} defaultErrorMessage="Please enter a valid phone number" /> ``` -------------------------------- ### Basic Usage of React-Phone-Input-2 Source: https://github.com/bl00mber/react-phone-input-2/blob/master/README.md Import the component and its CSS, then use it in your React application. Manage the phone number state using React's state management. ```jsx import PhoneInput from 'react-phone-input-2' import 'react-phone-input-2/lib/style.css' this.setState({ phone })} /> ``` -------------------------------- ### Handle Input Key Down Event Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/InputHandling.md Handles key presses on the input field. Fires `onEnterKeyPress` for the ENTER key and `onKeyDown` for any key press. Does not receive country data in the callback. ```javascript handleInputKeyDown = (e) => { const { keys, onEnterKeyPress, onKeyDown } = this.props; // Fire onEnterKeyPress for ENTER if (e.which === keys.ENTER) { if (onEnterKeyPress) onEnterKeyPress(e); } // Always fire onKeyDown for any key if (onKeyDown) onKeyDown(e); } ``` -------------------------------- ### handleSearchChange Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/Dropdown.md Updates the search state as the user types into the search input field. This method is crucial for real-time filtering of countries. ```APIDOC ## handleSearchChange ### Description Handles changes in the search input, updating the component's state with the new search value and resetting the highlighted country index. ### Method Signature ```javascript handleSearchChange(e: React.ChangeEvent): void ``` ### Usage Example ```javascript handleSearchChange = (e) => { const { currentTarget: { value: searchValue } } = e; const { preferredCountries, selectedCountry } = this.state; let highlightCountryIndex = 0; if (searchValue === '' && selectedCountry) { // When search is cleared, highlight the selected country const { onlyCountries } = this.state; highlightCountryIndex = this.concatPreferredCountries( preferredCountries, onlyCountries ).findIndex(o => o == selectedCountry); setTimeout(() => this.scrollTo(this.getElement(highlightCountryIndex)), 100); } this.setState({ searchValue, highlightCountryIndex }); } ``` ``` -------------------------------- ### Handle Flag Item Click Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/PhoneInput.md Handles the selection of a country from the dropdown list. It replaces the previous dial code with the new one, formats the number, and triggers the `onChange` event. ```javascript handleFlagItemClick(country: CountryObject, e: React.MouseEvent): void ``` -------------------------------- ### Initialize Country Data Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/CountryData.md Processes raw country data into structured country objects, generating format masks. If area codes are enabled, it creates separate entries for each area code. ```javascript function initCountries(countries: array, enableAreaCodes: boolean | string[], prefix: string, defaultMask: string, alwaysDefaultMask: boolean): [CountryObject[], CountryObject[]] ``` -------------------------------- ### Country Dropdown UI Structure Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/Dropdown.md Renders the complete dropdown UI including search field and country list. This structure is used internally by the component. ```jsx
          {enableSearch && (
        • )}
        • ...
        • ...
        • ...
        • No entries to show
        ``` -------------------------------- ### handleDoubleClick Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/InputHandling.md Handles the double-click event on the input field by selecting all the text within the input. ```APIDOC ## handleDoubleClick ### Description Handles the double-click event on the input field by selecting all the text within the input. ### Method `handleDoubleClick(e: React.MouseEvent): void` ``` -------------------------------- ### CountryData Class Definition Source: https://github.com/bl00mber/react-phone-input-2/blob/master/_autodocs/api-reference/CountryData.md Defines the constructor for the CountryData class, outlining all possible parameters for initializing and configuring country data management. ```javascript export default class CountryData { constructor( enableAreaCodes: boolean | string[], enableTerritories: boolean | string[], regions: string | string[], onlyCountries: string[], preferredCountries: string[], excludeCountries: string[], preserveOrder: string[], masks: object | null, priority: object | null, areaCodes: object | null, localization: object, prefix: string, defaultMask: string, alwaysDefaultMask: boolean ) } ```