Jie Hu
Jie Hu

Reputation: 539

react: reusable event handler for setstate

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

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30360

You could use the following syntax to achieve this:

handleFieldChange(fieldName, v){
    this.setState({
        draft: {...this.state.draft, [fieldname]: v}
    })
}

Upvotes: 1

Related Questions