PhoneInput: prettify input while typing

This commit is contained in:
Alex Gleason 2022-07-13 18:08:59 -05:00
parent f62dcc6650
commit ba98a8e82f
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
1 changed files with 10 additions and 2 deletions

View File

@ -1,4 +1,4 @@
import { parsePhoneNumber } from 'libphonenumber-js'; import { parsePhoneNumber, AsYouType } from 'libphonenumber-js';
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { CountryCode } from 'soapbox/utils/phone'; import { CountryCode } from 'soapbox/utils/phone';
@ -29,7 +29,15 @@ const PhoneInput: React.FC<IPhoneInput> = (props) => {
}; };
const handleChange: React.ChangeEventHandler<HTMLInputElement> = ({ target }) => { const handleChange: React.ChangeEventHandler<HTMLInputElement> = ({ target }) => {
setNationalNumber(target.value); // HACK: AsYouType is not meant to be used this way. But it works!
const asYouType = new AsYouType({ defaultCallingCode: countryCode });
const formatted = asYouType.input(target.value);
if (formatted === nationalNumber && target.value !== nationalNumber) {
setNationalNumber(target.value);
} else {
setNationalNumber(formatted);
}
}; };
// When the internal state changes, update the external state. // When the internal state changes, update the external state.