NightMarcher NightMarcher - 3 months ago 21
Javascript Question

ReactJS - Using .setState to change nested values

I'm attempting to set the state of a specific element (a checkbox) so that I can later pass this data back to a parent component that will in turn update a JSON object. I am able to set the state of higher level elements but I am not understanding how to access the nested values.

How do I use .setState to set the state of a specific element? Such as

this.state.data[0].checked


I'm attempting to set the state with something like this which would only update
data
at the moment:

handleChange: function(event) {
this.setState({data: event.target.value}});
},

Answer

It looks like you could use the immutability helpers, and if you are using a numerical / dynamic key, you should look at my question here.

Your solution would look something like this:

handleChange: function(index, event) {
  var data = React.addons.update(this.state.data, {
   [index]: {
     checked: {$set: event.target.checked}
   }
  });
  this.setState({
    data: data
  })
},

Notice the use of e.target.checked and not e.target.value for checkboxes to get the boolean state and not the value associated with the checkbox.

This is how you'd attach your function with the i index you'd have to set beforehand:

onChange={this.handleChange.bind(this, i)}