generated from frankstallone/minimal-bjj-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPhoneInput.tsx
More file actions
56 lines (49 loc) · 1.55 KB
/
PhoneInput.tsx
File metadata and controls
56 lines (49 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { useState } from 'react';
import { templateParser, templateFormatter, parseDigit } from 'input-format';
import ReactInput from 'input-format/react';
import CountrySelector from '@ui/CountrySelector';
import countryMasks from '@ui/flags/index.json';
/**
* PhoneInput component
* A controlled input component with input masking for phone numbers
* @returns A phone input component
*/
export default function PhoneInput() {
// Phone input value
const [value, setValue] = useState('');
// US phone number template
const [template, setTemplate] = useState('(xxx) xxx-xxxx');
const parse = templateParser(template, parseDigit);
const format = templateFormatter(template);
const handleChange = (
event: React.ChangeEvent<HTMLInputElement> | string | undefined,
) => {
setValue(typeof event === 'string' ? event : event?.target.value || '');
};
function updateTemplate(iso: string) {
const countryToUpdate = countryMasks.find(
(country: any) => country.iso === iso,
);
if (!countryToUpdate) return template;
if (Array.isArray(countryToUpdate.mask)) {
setTemplate(countryToUpdate.mask[0]);
setValue('');
} else {
setTemplate(countryToUpdate.mask);
setValue('');
}
}
return (
<div className="phone-input-container">
<CountrySelector updateTemplate={updateTemplate} />
<ReactInput
className="phone-input"
value={value}
onChange={handleChange}
placeholder="Enter phone number"
parse={parse}
format={format}
/>
</div>
);
}