Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
React: why is my cursor jumping to the end of the input field after the input is modified

I made a component to format phone number from XXXXXXXXXX to '(XXX) XXX-XXXX' here is my code


function formatPhoneNumber(phone) {
  const area = phone.slice(0, 3);
  const first = phone.slice(3, 6);
  const second = phone.slice(6, 10);

  let formattedTelephoneNumber = phone;

  if (phone.length >= 1) {
    formattedTelephoneNumber = `(${formattedTelephoneNumber}`;
  }

  if (phone.length >= 4) {
    formattedTelephoneNumber = `(${area}) ${first}`;
  }

  if (phone.length >= 7) {
    formattedTelephoneNumber = `(${area}) ${first}-${second}`;
  }

  return formattedTelephoneNumber;
}

function getRawPhoneNumber(inputValue) {
  return [...inputValue].filter((char) => /\d/.test(char)).join("");
}

export default function App() {
  const [value, setValue] = useState("");
  const handleInputChange = (e) => {
    const phoneNumber = getRawPhoneNumber(e.target.value);
    const formatted = formatPhoneNumber(phoneNumber);

    setValue(formatted);
  };
  return (
    <div className="App">
      <input value={value} onChange={handleInputChange} />
    </div>
  );
}

It works ok but when you are typing in the middle of a string - either add an extra number or delete one number, the cursor will jump to the end.

Does anyone know how to fix it?

here is a live demo you can play with https://codesandbox.io/s/phone-number-format-x4nnk?file=/src/App.js

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!