Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

192
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda