1

I'm facing something strange in React, and I think that might be possible to do it but I don't know how.

My goal: update a specific attribute of my component state, that can be a nested attribute. But! I want to update it dynamically (working with a onChange call on a bunch of inputs, don't want to code 30 onChange functions, I want to code a generic one).

Example that works:

this.state = { value: 0 }

Then:

var attribute = 'value'
var value = 'myvalue'
this.setState({[attribute]:value})

Example that does not work:

this.state = { nested: { value: 0 } }

Then:

var attribute = 'nested.value'
var value = 'myvalue'
this.setState({[attribute]:value})

I can have potentially as many nesting levels as possible. I want to find a generic and easy to afford method to deal with it.

I created a JSFiddle wich reproduces this problem as I'm trying to implement it, with onchange function: http://jsfiddle.net/n61kv6gy/

Does anyone has an idea?

Yoann B
  • 123
  • 2
  • 12
  • 1
    Have you looked into `update`? Related: http://stackoverflow.com/questions/25008322/updating-deep-reactjs-state – Andrew Li Oct 18 '16 at 14:07

2 Answers2

2

If I understood your question yo can try something like this in your onChange function:

onChange(value,e) {
  let oldState = this.state.nested.nestedAgain;
  let newState = this.state.nested.nestedAgain;
  newState[value] = e.target.value;

  this.setState({oldState: newState})
}

First clone your state, then make a change and at the end update the state.

Here is jsfiddle

Boky
  • 11,554
  • 28
  • 93
  • 163
  • Hi and thanks for your answer. That can do partially the job. – Yoann B Oct 18 '16 at 15:22
  • Let's assume that we have a state structured like this: – Yoann B Oct 18 '16 at 15:23
  • (ok thank you stackoverflow auto post comments...) this state: { value1: 1, nested: { value2: 2, nestedagain: { } } – Yoann B Oct 18 '16 at 15:24
  • Thanks Boky, I updated the JsFiddle with an html representation of the state and initialized it, and I added controls to show you the three cases i can have: http://jsfiddle.net/n61kv6gy/4/ – Yoann B Oct 20 '16 at 09:42
0

OK stack overflow comment function is very lacky. I answer to @Boky here:

Hi and many thanks for your answer. That does partially the job. How would you modify the code to allow us to bind these 3 properties?

{
   value1: 1,
   nested: {
      value2: 2,
      nestedAgain: {
         value3: 3
      }
   }
}
Yoann B
  • 123
  • 2
  • 12