react setState with dynamic key

Basic rule is:

We can use Computed property names concept and use any js expression to compute the object property name dynamically. For that we need to put the expression inside [].

Like this:

var obj = {
   [10 * 20 + 1 - 5]: "Hello"
};

console.log('obj = ', obj);

Solution:

As per the code you posted, you need to put e.target.id inside [], like this:

onChange(e) {
    this.setState({
      [e.target.id]: e.target.value
    })
}

Or we can create that object first, then pass that object to setState function, like this:

onChange(e) {
    let obj = {};
    obj[e.target.id] = e.target.value
    this.setState(obj);
}

Also you don’t need the prevState. You can directly update the state variable with new value.prevState is required only when new state value is dependent on previous state value, like in case of counter.

Leave a Comment