Я использую react-text-mask и Input antd. I have a problem. When I want to use a phone number mask, when I delete a character from the middle of the line, my cursor moves to the beginning of the line. I solved this problem by saving the cursor position. But in the end the mask input doesn't work for me. I want to enter the phone number 1234567890, I enter it from the keyboard. I get (234) 789-0651, because the position of the cursor does not ignore ( and space. how to fix this? the solution should work for any input mask.
export const MaskedInput = () => {
const [inputValue, setInputValue] = useState("");
const inputRef = useRef(null);
const [cursor, setCursor] = useState();
const mask = [
"(",
/[1-9]/,
/[0-9]/,
/[0-9]/,
")",
" ",
/[0-9]/,
/[0-9]/,
/[0-9]/,
"-",
/[0-9]/,
/[0-9]/,
/[0-9]/,
/[0-9]/,
];
useEffect(() => {
inputRef.current?.setSelectionRange(cursor, cursor);
}, [cursor]);
const handleChange = (event) => {
const { value } = event.target;
const { conformedValue } = conformToMask(value, mask, {
guide: true,
keepCharPositions: true, // Set to true to maintain character positions
});
setInputValue(conformedValue);
setCursor(event.target.selectionStart);
};
return (
<Input
ref={(node) => {
inputRef.current = node?.input; // Сохраняем реф на элемент input
if (typeof ref === "function") {
ref(node);
}
}}
value={inputValue}
onChange={handleChange}
placeholder="(123) 456-7890"
/>
);
};