3

This is how I use dynamic setState but what if I want to prefix the state name?

handleChange(field, value) {
    this.setState({ [field]: value });
}

<input
  onChange={e => this.handleChange('fname', e.target.value)}
/>
<input
  onChange={e => this.handleChange('lname', e.target.value)}
/>

Like I want to produce this.state.my_fname and this.state.my_lname.

1
  • in handleChange first param field is a string. you can concat like { ['my' + field]: value } Commented Jun 19, 2018 at 1:47

1 Answer 1

6

Does this achieve what you're after?

handleChange(field, value) {
    this.setState({ [`my_${field}`]: value });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.