Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react setState with dynamic key

Tags:

reactjs

I have the following snippet of code:

onChange(e) {
    e.persist
    this.setState((prevState) => {
      prevState[e.target.id] =  e.target.value
      return prevState
    })
  }

the how would i set the state for each key using something like the code above.

this is the initial state:

 this.state = {
      heading: this.props.match.params.length > 1 ? "Edit Post" : "Create Post",
      title: '',
      category: '',
      body: '',
      author: ''
    }
like image 443
Strahinja Ajvaz Avatar asked Oct 16 '17 13:10

Strahinja Ajvaz


1 Answers

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.

like image 101
Mayank Shukla Avatar answered Oct 01 '22 12:10

Mayank Shukla