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

Advertisements

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 🙂

<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

Leave a ReplyCancel reply