Ad

How Component Can Remove/delete Itself From DOM?

- 1 answer

Let's say I have a following JSX code:

var List = React.createClass({
  render: function() {
    var Items = this.props.data.map(function(item) {
      return (
        <Item key={item.id}>
          {item.text}
        </Item>
      );
    });
    return (
      <div className="items">
        {Items}
      </div>
    );
  }
});

var Item = React.createClass({
  handleDelete: function(e) {
    e.preventDefault();

    // Delete this (only this) component completely (remove it from DOM).
  },
  render: function() {
    return (
      <div className="item">
          {this.props.children}
          <button className="delete" onClick={this.handleDelete}>Delete</button>
      </div>
    );
  }
});

ReactDOM.render(
  <List data={Array of items} />,
  document.getElementById('content')
);

My question is: how items can completely remove/delete themselves in their own handleDelete() function?

Ad

Answer

One solution would be to have the container component (ie List) handle the onDelete functionality, and then update its state (keep track of deleted items). Then in your List's render() function, you can filter out any deleted items:

var List = React.createClass({
  getInitialState: function () {
    return { deleted: [] };
  },

  onDelete: function (id) {
    this.setState({ deleted: this.state.deleted.concat([id]) });
  },

  render: function() {
    var Items = this.props.data
      .filter(item => this.state.deleted.indexOf(item.id) === -1)
      .map(item => {
        return (
          <Item key={item.id} id={item.id} onDelete={id => this.onDelete(id)}>
            {item.text}
          </Item>
        );
      });

    return (
      <div className="items">
        {Items}
      </div>
    );
  }
});

var Item = React.createClass({
  render: function() {
    return (
      <div className="item">
          {this.props.children}
          <button className="delete" onClick={() => this.props.onDelete(this.props.id)}>Delete</button>
      </div>
    );
  }
});

ReactDOM.render(
  <List data={Array of items} />,
  document.getElementById('content')
);
Ad
source: stackoverflow.com
Ad