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

207
Visualizações
react - not able to update state in input value

I am learning react and I want to create a simple form where the input value changes and updates once the user types it in. I have this code where the input value updates the state when it is being typed, but when I press enter, the old state returns. I did lots of googling but can't seem to make it work. I have tried it with a submit button in the form, but that doesn't make a difference. I would like to make it work without a submit button as in the value changes and updates onChange only. What am I not seeing?

import React, { useState } from 'react';

function App() {
 
  const [value, setValue] = useState('John');
  
  const handleInputOnChange =(e)=> {
    setValue(e.target.value)
  };

  return (
    <div className="App">
      <form>
           <label>
               Name:
               <input value={value} onChange={handleInputOnChange}/>
           </label>
       </form>
      </div>
  );
}

export default App;

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It is happening because of the form tag. Whenever you hit enter the form will be submitted by default and the value of the input will be back to its initial value.

There are two ways you can stop this from happening.

1.) Remove the form tag from your App component.

2.) Add onSubmit function to the form to handle the form when it is submitted like below.

<form onSubmit={onSubmit}>...</form>

And the function to handle the form is as below:

const onSubmit = (e) => {
  e.preventDefault()
}

The preventDefault method will stop the default behavior of the form when it is submitted.

about 4 years ago · Juan Pablo Isaza Relatório
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