Skip to content

Commit

Permalink
Update logic to store and update phone number code
Browse files Browse the repository at this point in the history
  • Loading branch information
roma-claudio committed Jul 5, 2024
1 parent 73b9fb8 commit 15eb87d
Showing 1 changed file with 21 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
useId,
useMemo,
useRef,
useState,
type ChangeEvent,
type ClipboardEvent,
type ComponentType,
Expand Down Expand Up @@ -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 ||
Expand All @@ -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);
Expand Down Expand Up @@ -378,6 +395,7 @@ export const PhoneNumberInput = forwardRef<
options={options}
onChange={eachFn<[ChangeEvent<HTMLSelectElement>]>([
countryCode.onChange,
handleOptionChange,
handleChange,
])}
ref={applyMultipleRefs(
Expand Down

0 comments on commit 15eb87d

Please sign in to comment.