Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify the order of items in ReactCSSTransitionGroup?

Is it possible to specify the order of items in a ReactCSSTransitionGroup?

Consider a list of items which their order is important. If you want to show one item and hide its adjacent with one action, ReactCSSTransitionGroup confuses their order. Take a look the following fiddle, the items are supposed to be [1, 2, 3, 4, 5].

http://jsfiddle.net/mehranziadloo/kb3gN/15519/

Is it possible to tell ReactCSSTransitionGroup (or ReactTransitionGroup) the sequence of items?

like image 286
Mehran Avatar asked Jul 05 '16 00:07

Mehran


1 Answers

The ReactCSSTransitionGroup just animates changes in DOM, it doesn't care about order. Your state changes from odd to even numbers, there is no moment when it contains sorted array with all the numbers. You can work around it by modifying state in different way, temporary saving old items for animation purposes, something like that:

switch: function() {
  var newItems;
  if (this.state.items[0] % 2 !== 1) {
    newItems = [1, 3, 5];
  }
  else {
    newItems = [2, 4];
  }
  this.setState({
    items: newItems,
    previousItems: this.state.items
  }, function() {
    this.setState({
      previousItems: []
    })
  });
}

After that, you need to modify your render method:

render: function() {
  var currentItems = this.state.items.concat(this.state.previousItems).sort();
  var items = currentItems.map(function(item, i) {
    return (
      <div key={item}>
        {item}
      </div>
    );
  }.bind(this));
  return (
    <div>
      <button onClick={this.switch}>Switch</button>
      <ReactCSSTransitionGroup transitionName="example" transitionEnterTimeout={1000} transitionLeaveTimeout={1000}>
        {items}
      </ReactCSSTransitionGroup>
    </div>
  );
}

Here is an updated fiddle: http://jsfiddle.net/ny5La5ky/

like image 140
const314 Avatar answered Oct 10 '22 22:10

const314