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 which reproduces this problem as I'm trying to implement it, with onchange function: http://jsfiddle.net/n61kv6gy/

Does anyone have an idea?

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Hi and thanks for your answer. That can do partially the job.
Let's assume that we have a state structured like this:
(ok thank you stackoverflow auto post comments...) this state: { value1: 1, nested: { value2: 2, nestedagain: { } }
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: jsfiddle.net/n61kv6gy/4
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
      }
   }
}

1 Comment

See updated answer. You can maybe try something like that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.