Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!