Home > other >  input handelChange on object data
input handelChange on object data

Time:01-23

Here i have a state Details containing a object with name:'' age:'' phone:'' etc ... and a handlechange function , which whenever there's a change in input it should update the Details . there is a problem with way i wrote the line setDetails({...Details, e.target.name : e.target.value}

i tried this

function Personal() {
    const [Details, setDetails] = useState({ name:'hahaha' ,age:20 ,phone:0000000000});
  
    const handleChange = (e)=>{
        setDetails({...Details, e.target.name : e.target.value})
    }
  
    return (
    <div className='personal-details'>
      <h2>Personal Details</h2>
      <input type="text" name='name' onChange={handleChange}/>
      <input type="number" name='age' onChange={handleChange}/>
      <input type="number" name='phone' onChange={handleChange}/>
      
      

    </div>
  )
}

what i want is whenever there's a change i the input it should update it in the Details without changeing the exsisting datas.

thank u

CodePudding user response:

One problem with your code is that you are trying to access the properties of the event object (e.target.name and e.target.value) within the object destructuring assignment. Instead, you should use the square bracket notation to access the properties dynamically like this ;

setDetails({...Details, [e.target.name]: e.target.value})

This will correctly access the name and value properties of the event target, and update the appropriate key in the Details object.

  • Related