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

218
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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