Question

I'm trying to implement a form where I can delete specific inputs using React. The problem is, react doesn't seem to be rendering the information correctly. This is my render function:

render: function(){
  var inputItems;
    if (this.state.inputs){
      inputItems = this.state.inputs.map(function(input){
      console.log(input)
      return (
        <Input
          input={input}
          onDestroy={this.destroy.bind(this, input)}
          onEdit={this.edit.bind(this, input)}
          editing={this.state.editing === input.id}
          onCancel={this.cancel} />
      );
    }, this);
  }

(...)
// this isn't the actual render return
return {inputItems}

and my destroy function:

destroy: function (input) {
  var newInputs = this.state.inputs.filter(function (candidate) {
    return candidate.id !== input.id;
  });

  this.setState({
    inputs: newInputs
  });
},

The actual destroy function is getting called through a child component via <a href="#" onClick={this.props.onDestroy}>(Remove)</a>. The interesting thing is that when I console log my inputs, as seen in the render function, the correct inputs are shown - the one I called the destroy function on is gone. But the incorrect inputs are rendered - it's always the very last one that disappears, not the one I called the destroy function on. So for example, I'll initially log:

First Name
Last Name
Email

and call the destroy function on the Last Name. The console.log will show:

First Name
Email

but the actual rendered information will show:

First Name
Last Name

Thanks!

Was it helpful?

Solution

Figured it out. Has to do with React child reconciliation. Added a key={input.id} to the <Input> tag and it works.

More information here under child reconciliation and dynamic children. http://facebook.github.io/react/docs/multiple-components.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top