I am trying to figure out if it's possible to capture input/checkbox onchange events and update the state from the same function? The reason behind this is that I am still learning React and would like to learn how to save the state properly.
I've tried to save the state the following way, but I am probably making some mistakes:
constructor(props) {
super(props);
this.state = {
list: [],
test: {
text: "placeholder",
age: null
},
anotherTest: {
name: "",
info: ""
}
};
handleChange = e => {
var target = e.target.name;
var value = e.target.value;
this.setState({
...this.state,
[target]: value
});
};
And the render:
<input name="text" value={this.state.test.text} onChange={e => this.handleChange(e)} />
<input name="name" value={this.state.anotherTest.name} onChange={e => this.handleChange(e)} />
I am in this example creating a new state instead of updating the targeted object.
Whole test enviroment: