I have a form containing two fields of input; name and mark
I want to update a property depending on which field is changing, instead of making two (will be increasing) functions to handle each field individually.
Here is the current code which only updates the name
property with the value:
handleStudentChange(e) {
console.log(e.target)
var value = e.target.value
console.log("value: ", value)
var field = e.target
//e.target returns <input id="mark1" class="form-control" type="number" placeholder="Mark 1" value="40">
this.setState({
activeStudent: {
...this.state.activeStudent,
name: value
}
})
}
Field can take the value of the target property name such as name
or mark1
by tapping into the e.target.id
property. Is there a way to cast field
as the property to use field:value or any other better way of going about the whole thing? Thanks in advance 🙂
2
Answers
the important thing to use this approach, you should have input
name
prop set as the state property. for example, ifactiveStudent
has "name" property, corresponding input should be setYou can set a attribute for key value.
Then you can get that attribute by calling e.target.getAttribute(‘key’).