1

How can I remove an item from the data when clicking the div inside Item?

var App = React.createClass({
  ...
  handleSubmit: function(e) {
    this.state.data.push({ x: this.state.x });
  }
});

The item's class to remove.

var Item = React.createClass({
    render: function() {
      return (
        <li>
          <div onClick={this.removeItem}></div>
        </li>
      )
    }
});

The list class.

var ItemList = React.createClass({
  render: function() {
    var items = this.props.data.map(function(item) {
      return <Item x={item.x}>
    });
  }
});

1 Answer 1

4

Since the App component manages the data array, you need to bubble the remove request all the way from Item to ItemList to App.

So pass a callback from App to ItemList:

var App = React.createClass({
  ...
  removeItem: function(index) {
    this.setState(function(state) {
      var newData = state.data.slice();
      newData.splice(index, 1);
      return {data: newData};
    });
  },
  render: function() {
    return (
      ... <ItemList onRemove={this.removeItem} /> ...
    );
  },
  ...
});

And pass that callback into each Item:

var ItemList = React.createClass({
  render: function() {
    var items = this.props.data.map(function(item, index) {
      return <Item x={item.x} index={index} onRemove={this.props.onRemove}>
    }.bind(this));
    ...
  }
});

Finally, call onRemove from Item:

var Item = React.createClass({
  ...
  removeItem: function() {
    this.props.onRemove(this.props.index);
  },
});
Sign up to request clarification or add additional context in comments.

6 Comments

In your answer, shouldn't 'removeItem' be 'onRemove'?
And why are you using 'this.props.x' as a parameter to onRemove
Yeah, sorry. I found a few errors just after posting. I think I have caught most of them now, but let me know if I missed anything. :)
Why do you have bind(this)?
I refer to this.props inside the callback, and the callback isn't guaranteed to have the same this unless you bind it.
|

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.