Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda