I have a component that stores a contact object as state - {firstName: "John", lastName: "Doe", phone: "1234567890} I want to create a form to edit this object but if I want the inputs to hold the value of the original contact parameter, I need to make each input a controlled component. However, I don't know how to create a handleChange function that will adjust to each parameter because my state only holds {contact: {...}}. Below is what I currently have -
getInitialState: function () {
return ({contact: {}});
},
handleChange: function (event) {
this.setState({contact: event.target.value });
},
render: function () {
return (
<div>
<input type="text" onChange={this.handleChange} value={this.state.contact.firstName}/>
<input type="text" onChange={this.handleChange} value={this.state.contact.lastName}/>
<input type="text" onChange={this.handleChange} value={this.state.contact.lastName}/>
</div>
);
}
I wish in my handleChange I can do something like
handleChange: function (event) {
this.setState({contact.firstName: event.target.value });
}
<input>
elements often have a property called name. We can access this name property from the event object that we receive from an event handler:Write a generalized change handler
source
ES6 one liner approach
The neatest approach
Here is an approach that I used in my simple application. This is the recommended approach in React and it is really neat and clean. It is very close to ArneHugo's answer and I thank hm too. The idea is a mix of that and react forms site. We can use name attribute of each form input to get the specific propertyName and update the state based on that. This is my code in ES6 for the above example:
The differences:
We have less code here and vey smart way to get any kind input from the form because the name attribute will have a unique value for each input. See a working example I have in CodPen for my experimental blog application in its early stage.
There are two ways to update the state of a nested object:
You can see how it works in this JS Fiddle. The code is also below:
Here is generic one;
And use like this;