0

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}});
  },
1
  • could you share some codes? Commented Aug 13, 2016 at 14:11

1 Answer 1

1

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)}
Sign up to request clarification or add additional context in comments.

1 Comment

this is exactly what i was looking for. I updated your post with a couple of small syntax edits and had to throw in that comma at the end to make SO happy. Thanks!

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.