How To Update Object In State From E.target.name
I am trying to input data from a form like this -
Company Position
functions.setDSolution 1:
e.target.name
is company.position
, you can't set nested property like obj["company.position"]
, you'll have to split it :
<input
name="company.position"
type="text"
onChange={e => functions.setData(e)}
value={data.company.position}
/>;
const handleStateChange = e => {
e.preventDefault();
const [section, key] = e.target.name.split(".");
// section is : company
// key is : position
if (key) {
// if you have nested keys to update
setValues({
...form,
[section]: {
...form[section],
[key]: e.target.value
}
});
} else {
// if you're updating on the first level
setValues({
...form,
[section]: e.target.value
});
}
};
Solution 2:
const nested = e.target.name.split(".");
const [section, key] = nested;
if(nested.length > 2){
let total = nested.length;
let ultimo = nested[total-1];
saveclinicHistory({
...clinicHistory,
[section]: {//patient
...clinicHistory[section],
[key]: {//address
...clinicHistory[section][key],
[ultimo]:e.target.value
}
}
});
Post a Comment for "How To Update Object In State From E.target.name"