We can use Computed property names concept to compute the object property name dynamically. For that we need to put the expression inside [].
When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.
For your state
this.setState({
formInput: {
...this.state.formInput,
[event.target.name]: event.target.value
}
})
Sandbox for your reference: https://codesandbox.io/s/react-basic-example-p7ft8
import React, { Component } from "react";
export default class Login extends Component {
state = {
formInputs: {
email: "",
password: ""
}
};
handleOnChange = event => {
this.setState({
formInput: {
...this.state.formInput,
[event.target.name]: event.target.value
}
});
};
render() {
return (
<form>
<label>Email</label>
<input type="text" name="email" onChange={this.handleOnChange} />
<label>Password</label>
<input type="password" name="password" onChange={this.handleOnChange} />
</form>
);
}
}