Alan Jenshen
Alan Jenshen

Reputation: 3239

dynamic setState and get state using es6 in react

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.

Upvotes: 2

Views: 685

Answers (1)

hmnzr
hmnzr

Reputation: 1430

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)}
/>

Upvotes: 2

Related Questions