import React, {useState} from 'react'; import {PhoneNumberUtil} from 'google-libphonenumber'; import { InputAdornment, MenuItem, Select, TextField, TextFieldProps, Typography, } from '@mui/material'; import { CountryIso2, defaultCountries, FlagImage, parseCountry, usePhoneInput, } from 'react-international-phone'; import 'react-international-phone/style.css'; interface Props { value: string; required?: boolean; onChange: ({ phone, country, }: { phone: string; country: CountryIso2 | ''; error: boolean; }) => void; label: string; } const phoneUtil = PhoneNumberUtil.getInstance(); const isPhoneValid = (phone: string) => { try { return phoneUtil.isValidNumber(phoneUtil.parseAndKeepRawInput(phone)); } catch (error) { return false; } }; const PhoneInput = ({ value, onChange, label, required, ...textFieldProps }: Omit & Props) => { const [phone, setPhone] = useState(value); const browserLocales = navigator.language.split('-'); const defaultCountry = browserLocales[browserLocales.length - 1].toLowerCase(); const {inputValue, handlePhoneValueChange, inputRef, country, setCountry} = usePhoneInput({ defaultCountry: defaultCountry || defaultCountries[0][1], value: phone, countries: defaultCountries, onChange: ({phone, country}) => { setPhone(phone); if (isPhoneValid(phone)) onChange({phone, country: country.iso2, error: false}); else onChange({phone: '', country: '', error: true}); }, }); return ( ), }} /> ); }; export default PhoneInput;