frontend/lib/phoneNumbers.tsx (view raw)
1import {
2 CountryIso2,
3 defaultCountries,
4 getActiveFormattingMask,
5 parseCountry,
6 } from 'react-international-phone';
7
8export const getFormatedPhoneNumber = ({
9 phone,
10 phoneCountry,
11 }: {
12 phone: string;
13 phoneCountry: CountryIso2;
14 }): string => {
15 if (!phoneCountry || phoneCountry === '') return phone;
16 const parsedCountry = parseCountry(
17 defaultCountries.find(country => country[1] === phoneCountry)
18 );
19 const activeMask = getActiveFormattingMask({phone, country: parsedCountry});
20 let splittedPhone = phone.split(parsedCountry.dialCode)[1].split('');
21
22 const maskWithValues = activeMask
23 .split('')
24 .map(char => {
25 if (char === '.') {
26 return splittedPhone.shift();
27 }
28 return char;
29 })
30 .join('');
31
32 return `+${parsedCountry.dialCode} ${maskWithValues}`;
33 };