reactjs – How to update an element of an array in React?

Question:

Using ReactJS I need to update an element of an array using the immutability helpers .

I have something like this:

this.setState(React.addons.update(this.state.collection[index], {
  property: { $set: !this.state.collection[index].property }
}));

In which index is effectively the index of the element to modify in the collection, and property a boolean that I want to negate in the update.

The problem is that the code is not modifying the property of the collection item, but rather it is generating a property property on the this.state object – so this.state ends up being something like {collection: [...], property: true} .

In Nested Collections it says that it would have to use a hash with the index of the element as a key, but I have the index in a variable, from what I understand that the update is ambiguous:

this.setState(React.addons.update(this.state, {
  collection: {
    index: {
      property: { $set: !this.state.collection[index].property }
    }
  }
}));

But it tells me that Cannot read property 'property' of undefined (i.e. this.state.collection doesn't have a property index , which is understandable).

How can i solve this?

I know I should use $apply instead of $update , but that's not the point of the question 🙂

Answer:

On StackOverflow in English , Felix Kling answered me that the dynamic properties of ES2015 can be used:

this.setState(React.addons.update(this.state, {
  collection: {
    [index]: { // <--
      property: { $set: !this.state.collection[index].property }
    }
  }
}));
Scroll to Top