Reputation: 539
I have a react component with some fields (dropdowns, text input areas etc.) each has onclick handler like:
handleTitleChange(v){
this.setState({
draft: {...this.state.draft, title: v}
})
}
handleDescriptionChange(v){
this.setState({
draft: {...this.state.draft, description: v}
})
}
...... about 5 more
Notice here the state is an object with different keys. How I can make a unique handler with the field of the state object passed to the handle function? something like:
handleFieldChange(fieldName, v){
this.setState({
draft: {...this.state.draft, <fieldName>: v}
})
}
So I can reuse it in different component?
Upvotes: 1
Views: 375
Reputation: 30360
You could use the following syntax to achieve this:
handleFieldChange(fieldName, v){
this.setState({
draft: {...this.state.draft, [fieldname]: v}
})
}
Upvotes: 1