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

Asked

Viewed 87 times

0

I have a component and the following state:

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

In form fields, 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 one doesn’t 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 not on the attributes belonging to the address.

How to solve this?

Thanks in advance. :)

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 a if and solves, but if you want something that is more dynamic, that you can reuse in other places without changing and that can access N children of the object:

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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.