I have a field like this:
const updatedForm = Object.assign({}, this.state.form)
updatedForm[name] = value;
Is there a way I can use the spread operator or ES6 to further simplify this?
I have a field like this:
const updatedForm = Object.assign({}, this.state.form)
updatedForm[name] = value;
Is there a way I can use the spread operator or ES6 to further simplify this?
Yes you can:
const updatedForm = { ...this.state.form, [name]: value };
Note the square brackets around [name]
. This is due to the use of dynamic property names in your original code - this is how you do it in a literal.
This would have the same effect as:
const updatedForm = {...this.state.form}
updatedForm[name] = value
Which in a sense is shorter and achieves the same goal.
From @Felix Kling
const updatedForm = {
...this.state.form,
[name]: value
}
So you can define the new key-value pair during the creation of your newly spreaded object.
In practice, I'm assuming with React
. you could do something like:
class Form extends React.Component{
state = {
form: {
name: "",
age: ""
}
}
handleOnChange = (e) => {
const { name, value } = e.target
const updatedForm = {
...this.state.form,
[name]: value
}
this.setState({
form: updatedForm
})
}
render(){
const { form } = this.state
return(
<div>
<form>
<input name="name" value={form.name} onChange={this.handleOnChange}/>
<input name="age" value={form.age} onChange={this.handleOnChange}/>
</form>
</div>
)
}
}
See sandbox: https://codesandbox.io/s/objective-galois-ifogc
You can do this in one line using Object.assign
too:
const updatedForm = Object.assign({}, this.state.form, { [name]: value })