skip to Main Content

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


  1. Chosen as BEST ANSWER

    I ended up coming up with a different solution to solve this.

        const handlePhoneInput = (e) => {
            const regex = /[0-9-()s]/;
            if (e.target.value === '' || regex.test(e.target.value)) {
                const formattedPhone = formatPhoneNumber(e.target.value);
                setPhone(formattedPhone);
            }
        }
    
        const formatPhoneNumber = (phoneNumberString) => {
            var cleaned = ('' + phoneNumberString).replace(/D/g, '');
            var match = cleaned.match(/^(1|)?(d{3})(d{3})(d{4})$/);
            if (match) {
                var intlCode = match[1] ? '+1 ' : '';
                return `${intlCode}(${match[2]}) ${match[3]}-${match[4]}`;
            }
            return phoneNumberString;
        } 
    

  2. try this code below :

    const handlePhoneInput = (e) => {
    const input = e.target;
    const startPosition = input.selectionStart;
    const formattedPhone = formatPhoneNumber(input.value);
    setPhoneState({...phoneState, [input.id]: formattedPhone}, () => {
    // Restore the cursor position after the state has been updated
    input.selectionStart = startPosition;
    input.selectionEnd = startPosition;
     });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search