diff --git a/packages/circuit-ui/components/PhoneNumberInput/PhoneNumberInput.tsx b/packages/circuit-ui/components/PhoneNumberInput/PhoneNumberInput.tsx index 105453b09e..6ebe0391de 100644 --- a/packages/circuit-ui/components/PhoneNumberInput/PhoneNumberInput.tsx +++ b/packages/circuit-ui/components/PhoneNumberInput/PhoneNumberInput.tsx @@ -20,6 +20,7 @@ import { useId, useMemo, useRef, + useState, type ChangeEvent, type ClipboardEvent, type ComponentType, @@ -232,6 +233,24 @@ export const PhoneNumberInput = forwardRef< [countryCode.options, locale], ); + const [optionCode, setOptionCode] = useState(''); + + const handleOptionChange = () => { + const selectedCountryCode = countryCodeRef?.current?.value; + if (selectedCountryCode) { + return; + } + const newOption = countryCode.options + // Match longer, more specific country codes first + .sort((a, b) => a.code.length - b.code.length) + .find(({ country }) => country === selectedCountryCode); + + if (!newOption) { + return; + } + setOptionCode(newOption.code); + }; + const handleChange = () => { if ( !onChange || @@ -241,9 +260,7 @@ export const PhoneNumberInput = forwardRef< return; } const phoneNumber = normalizePhoneNumber( - countryCode.options.find( - ({ country }) => country === countryCodeRef?.current?.value, - )?.code as string, + optionCode, subscriberNumberRef.current.value, ); onChange(phoneNumber); @@ -378,6 +395,7 @@ export const PhoneNumberInput = forwardRef< options={options} onChange={eachFn<[ChangeEvent]>([ countryCode.onChange, + handleOptionChange, handleChange, ])} ref={applyMultipleRefs(