Middle
export const usePhoneMask = ({ mask, initialValue, maskPlaceholder, }: UsePhoneMaskParams): UsePhoneMaskReturn => { // code here };
sobes.tech AI
Answer from AI
The usePhoneMask function is a React hook that helps apply a mask to a phone number during input.
Example implementation in TypeScript:
import { useState, useEffect } from 'react';
interface UsePhoneMaskParams {
mask: string; // for example, '+7 (___) ___-__-__'
initialValue?: string;
maskPlaceholder?: string; // character for filling, e.g., '_'
}
interface UsePhoneMaskReturn {
value: string;
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
}
export const usePhoneMask = ({ mask, initialValue = '', maskPlaceholder = '_' }: UsePhoneMaskParams): UsePhoneMaskReturn => {
const [value, setValue] = useState(initialValue);
const formatValue = (input: string) => {
let i = 0;
const def = mask.replace(/[^_\d]/g, '');
let val = input.replace(/\D/g, '');
let formatted = '';
for (const char of mask) {
if (char === maskPlaceholder) {
if (val[i]) {
formatted += val[i];
i++;
} else {
formatted += maskPlaceholder;
}
} else {
formatted += char;
}
}
return formatted;
};
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const inputVal = e.target.value;
const formatted = formatValue(inputVal);
setValue(formatted);
};
useEffect(() => {
if (initialValue) {
setValue(formatValue(initialValue));
}
}, [initialValue]);
return { value, onChange };
};
This hook takes a mask, initial value, and filler character, returning the current value and a change handler that formats user input according to the mask.