14

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: ''
    }
SherylHohman
  • 16,580
  • 17
  • 88
  • 94
Strahinja Ajvaz
  • 2,521
  • 5
  • 23
  • 38
  • so what is the question? the code in the `onChange` will set a dynamic state key as the id of your event element. you don't need to persist the event - just do `const { target: { value, id } } = e` then just use `id` and `value` – Dimitar Christoff Oct 16 '17 at 13:23
  • Possible duplicate of [Reactjs setState() with a dynamic key name?](https://stackoverflow.com/questions/29280445/reactjs-setstate-with-a-dynamic-key-name) – Damjan Pavlica Feb 12 '18 at 15:53

1 Answers1

25

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.

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142