I'm currently starting to learn ReactJS and have run into some trouble updating an array.
Currently I have a searchable list of contacts which is working fine. But using the input box below the list I am trying to add additional items to the list using the update() function.
Sample of what I've got so far for the update function is below. Ideally at some point the updated content would come from the input box to the left of the button, but currently I'm just trying to push a static item as a test.
updateContact: function(e){
e.preventDefault();
var newItems = React.addons.update(this.state.initialItems, {$push: ["New Item"]})
return;
},
Any help or direction would be greatly appreciated, and a full JSFiddle with the entire code can be found below.
JS Fiddle
You are not calling setState, so the component never re-renders:
updateContact: function(e){
e.preventDefault():
var newItems = React.addons.update(this.state.initialItems, {$push: ["New Item"]});
this.setState({
initialItems: newItems,
items: newItems
}); // update state
},
Note that update both, this.state.items, this.state.initialItems. I assume you are using items for the filtered list and initialItems for all items in the list.
Of course you have to replace "New Item" with the actual value of the text field.
I would also remove componentWillMount and simply set initialItems and items to the same value in getInitialState.
Also if you'd simply bind the handler directly to the button and remove the <form>, you don't have to deal with preventing the event. It seems a rather roundabout way to trigger the callback.
Cleaned up example: https://jsfiddle.net/f554xrh0/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With