Skip to content
Advertisement

Controlled from in React

I’m new in react and I’m a bit confused about how React runs update on every new input’s keystroke, for exapmpe, this is the form and I want to update the state on every keystroke

import React, {useState} from 'react';

let FormsPractice =()=>{
let  [data, updateData] =useState('')
  
 let handleChange =(event)=>{

     let {value} = event.target;
       
     updateData(value)
     }

    return(
        <div className ="container">
            <form >
                <input
                        type="text"
                        placeholder="Enter name"
                        name="name"
                        value={data}
                        onChange={handleChange}
                />
            
            </form>
        </div>
    )
}
export default FormsPractice

What I don’t understand here is the update cycle, my understanding is the following:

As the input’s value is tied to react state, the initial value of the input is obviously “”.

Now I come to the point:

=> when a keystorke happens, let’s suppose an “a” character is typed;

=> the handleChange method is invoked;

=> event.target.value, does it retrun “a” (as a value of the input’s own state) or does it return empty, because the value is tied to the state (value={data} I’m not sure what state is assigned to the value in this case) Hope I can understand this

Thank you

Advertisement

Answer

The onChange event handler is a prop that you can pass to <input> elements. and it listens to user input in real time.

whenever you type something into the input, React will trigger the function that you passed into the onChange which calls the function you passed as its parameter. in your case you’re calling handleChange . The event object passed into handleChange function contains all the detail about the input event.

in your case when you type ‘a’ in the input react will trigger handleChange this function update the state from data = “” and value={data} ==> value="" to data=”a” value={data} ==> value="a"

Advertisement