Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to remove child

Tags:

reactjs

I am struggling with a way to remove a child component from a list.

Here is a jsbin that shows what I have so far.

I have the following code in the render method of the parent component that generates a list like this:

var items = this.state.items.map(function(item, i) {
  return (
    <Todo description={item} key={item} onClick={this.handleRemove.bind(this, i)}/>);
}.bind(this));

The problem is that the evenhandler is not being called on click.

The other way of approaching this would be to have the click handler on the child component but I don't know how to remove the item from the parent component.

like image 948
dagda1 Avatar asked Nov 30 '14 20:11

dagda1


1 Answers

Click handlers can only be added to DOM-based components; if you want to add them to composite component, you have to pass them through to a DOM component, as such:

this.state.items.map(function(item, i) {
  return (
    <Todo description={item} key={item} onClick={this.handleRemove.bind(this, i)}/>);
}.bind(this));

// ...

var Todo = React.createClass({
  render: function() {
    return (
      <tr onClick={this.props.onClick}>
        <td>{this.props.description}</td>
      </tr>
    );
  }
});

This makes your jsbin's click handler fire, but the elements won't disappear until you add some CSS transitions (since you're using the ReactCSSTransitionGroup):

.example-leave {
  opacity: 1;
  transition: opacity .5s ease-in;
}

.example-leave.example-leave-active {
  opacity: 0.01;
}

Finally, to make the table animate correctly, you need to tell the transition group to use a tbody instead of the default span:

<table>
  <ReactCSSTransitionGroup transitionName="example" component="tbody">
    {items}
  </ReactCSSTransitionGroup>
</table>

See the working jsbin here: http://jsbin.com/dakenabehi/3/edit?css,js,console,output

like image 187
Michelle Tilley Avatar answered Sep 28 '22 00:09

Michelle Tilley