ReactJS Updating an Array

I am currently starting to learn ReactJS and am facing some issues while updating an array.

I currently have a contact list to find which is working fine. But using the input field below the list, I am trying to add additional items to the list using the update () function.

Below is an example of what I have for the update function. Ideally, at some point, the updated content will come from the input box to the left of the button, but currently I'm just trying to push a static element as a test.

  updateContact: function(e){
    e.preventDefault();
    var newItems = React.addons.update(this.state.initialItems, {$push: ["New Item"]})
    return;
  },

      

Any help or direction is greatly appreciated and a complete JSFiddle with all the code can be found below.

JS Fiddle

+3


source to share


1 answer


You don't call , so the component never re-renders: setState

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 the update both this.state.items

, this.state.initialItems

. I assume you are using items

for the filtered list and initialItems

for all the items in the list.

Of course, you have to replace "New Item"

with the actual value of the textbox.




I would also uninstall componentWillMount

and just set initialItems

and items

to the same value in getInitialState

.

Also, if you just bind the handler directly to the button and delete <form>

, you don't need to deal with event prevention. Seems like a pretty roundabout way to call the callback.

Cleanup example: https://jsfiddle.net/f554xrh0/

+4


source







All Articles