2

Recently I learn about you can handle multiple input event using dynamic state.

If have state like this

this.state = {
   name_1: 'john',
   name_2: 'james'
}

I can get my state like this

[1,2].forEach(obj, i), => (
  console.log(this.state[`person_${i}`]);
))

But what about setState? What is the syntax like? I used this and it worked.

//says i is dynamic

this.setState({
  [`person_${i}`]: ''
})

Why above code work? it look like array.

1 Answer 1

2

It's a new feature in ES6 Called ComputedPropertyName. You can initialize object with dynamic property names.

You can read more about this here.

In React ecosystem, it is commonly used to handle input changes:

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

<input
  onChange={e => this.handleChange('firstName', e.target.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.