miércoles, 12 de diciembre de 2018

React : Generic update fields.

Maybe the most commont task on react programming, is to update the value on the html component.

 We have to attacth the state property to the value property on the field in order to set the values, and we have to bind the Onchange property on the react component to a method that will update the value on the state.

   This how I implement this both properties,

  //Onsingle method for all the properties.
updateUserValues = (e,fieldname) => {
e.preventDefault();
//We clone the object
const newvalues = {
...this.state.usuarioinfo
};
//We update the field property
newvalues[fieldname]=e.target.value;
//We update the state
this.setState({
usuarioinfo :{
...newvalues
}
});
}



    <input name=""
value={props.usuarioinfo.phonenumber} <- bind="" component="" div="" of="" property="" the="" value="" we="">
//we bind the onchange property to our generic method, sending the e argument, and
// the fieldname that we are going to update.
onChange={(e) => props.updateUserValues(e,'phonenumber') }
type="text"/>