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

191
Visualizações
How to re-render React Input with formatted value after user put each character with OnChange

I have react input component that should only take number and commas. I was able to restrict users from inserting character, also I was able to get the numbers with commas in the useState. But I want to show commas in the input even though the users don't put them. For example, if a user put 100000, the input will automatically re-render to 100,000 in every onChange.

Below is my code:

    const regex = new RegExp("^[0-9,]*$");
    const [homePrice, setHomePrice] = useState( "100,000");
    
    const onChangeHomePrice = (e) => {
     setHomePrice(e.target.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
     console.log(homePrice);
    };

   return (
   <FormInput type="text" maxLength={10} value = {homePrice} placeholder="100,000" 
          onChange={onChangeHomePrice} 
          onKeyPress={(e) => {
          if (!regex.test(e.key)) {
             e.preventDefault();
             }
           }}         
   >
  </FormInput>
    )

How can I re-render the input with proper commas? In my code, when I put console.log(homePrice), I can see the commas. So, I put homePrice as input value :

value={homePrice}.

But this does not change the user input with proper commas.

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