How can I keep the cursor position in the right spot? When I type out the phone number and it gets to the parenthesis in the phone number, it starts typing the number from there and leaves the cursor position behind which makes it type an incorrect number.
import { TextField } from '@mui/material';
import { useStore } from '@shared/stores';
const PhoneInput = () => {
const { phone } = useStore();
const handlePhoneInput = (e) => {
const formattedPhone = formatPhoneNumber(e.target.value);
setPhone(formattedPhone);
}
const formatPhoneNumber = (value) => {
const newPhone = value.replace(/[^d]/g, '');
const phoneLength = newPhone.length;
if(phoneLength < 4) return newPhone;
if(phoneLength < 7){
return `(${newPhone.slice(0, 3)}) ${newPhone.slice(3)}`;
}
return `(${newPhone.slice(0, 3)}) ${newPhone.slice(3,6)}-${newPhone.slice(6,10)}`;
}
return (
<TextField
label="Phone number"
type="text"
id="phone"
onChange={handlePhoneInput}
data-testid={'phone'}
value={phone}
textFieldProps={{
inputMode: "numeric",
pattern: "[0-9]*",
maxLength: "14"
}}
/>
);
};
export default PhoneInput;
2
Answers
I ended up coming up with a different solution to solve this.
try this code below :