How to change a state in the following scenario with the OnChange event

0

I have a component and the following state:

this.state = {
    form : {
        name : '',
        username: '',
        email: '',
        phone: '',
        address: {
            street: '',
            suite: '',
            city: '',
            zipcode: ''
        }
    }
}

In the form fields, I use the following method in onChange:

handleChange(e) {
    const {name, value} = e.target;
    let copyState = Object.assign({}, this.state);
    copyState.form[name] = value;
    this.setState(copyState);
}

This is an example of a functional form field:

<input value={this.state.form.username} 
    onChange={this.handleChange} 
    name="username"
    type="text" 
    className="form-control" 
/>

This does not work:

<input value={this.state.form.address.street} 
   onChange={this.handleChange} 
   name="address.street"
   type="text"
   className="form-control" 
/>

The handleChange method works perfectly on the items: name, username, email, and phone, BUT in the attributes belonging to the address not.

How to solve this?

Thank you in advance. :)

    
asked by anonymous 05.01.2019 / 02:42

1 answer

0

When you run the line

copyState.form[name] = value;

What happens is

copyState.form['address.street'] = 'value of input';

and not

copyState.form['address']['street'] = 'value of input';

You can use if and resolve, but if you want something that is more dynamic, you can reuse it in other places without changing it and you can access the object's N children:

const {name, value} = e.target;

let copyState = Object.assign({}, this.state);

props = name.split('.');

lastProp = props.pop();

tmp = copyState.form;

for (prop of props) tmp = tmp[prop];

tmp[lastProp] = value;

this.setState(copyState);
    
05.01.2019 / 06:33