Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React useState hook is not updating values from the input field onChange

I unable to manage the state for the second component of a similar type with the useState hook.

name1 is working and name2 is not updating. How does one get name2 to update like name1 ? What am I missing here.

Will appreciate some help at understanding the concepts 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<body>
  <div id="root"></div>
  <script src="https://unpkg.com/react@16.12.0/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone@7.8.3/babel.js"></script>
  <script type="text/babel">
    function Greeting () {
      const [name, setName] = React.useState('')
      const [name2, setName2] = React.useState('')
      const handleChange = event => setName(event.target.value)
      const handleChange2 = event => setName2(event.target.value)
      return (
        <div>
          <form>
            <label htmlFor='name'>Name: </label>
            <input onChange={handleChange} id='name' />
          </form>
          {name ? <strong>Hello {name}</strong> : 'Please type your name'}
          <div>
            <form>
              <label htmlFor='name'>Name: </label>
              <input onChange='{handleChange2}' id='name' />
            </form>
            {name2 ? <strong>Hello {name2}</strong> : 'Please type your name'}
          </div>
        </div>
      )
    }

    ReactDOM.render(<Greeting />, document.getElementById('root'))
  </script>
</body>

>Solution :

You just wrapped the handler with ':

<input onChange='{handleChange2}' id='name' />

delete them and it will be good

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading