Skip to content
Advertisement

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;

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement