4

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!

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Note that if you use controlled components (facebook.github.io/react/docs/forms.html#controlled-components) your form will always match your model data and you won't have this issue even if you forget to use keys.

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.