3

I have been looking around for an example of adding items to a list with react and having it animate the newly added item, but not to the end of the list, but the beginning of the list. I found this example, but all the messing around I have done locally and online, I cant seem to get the item to animate when added to the first spot in the array. Here is a simple react todo add item. How can I get the item to add to the first spot, and do the animation to the first spot?

JS Fiddle: http://jsfiddle.net/kb3gN/13152/

var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;

var TodoList = React.createClass({
  getInitialState: function() {
    return {items: ['hello', 'world', 'click', 'me']};
  },
  handleAdd: function() {
    var newItems =
      this.state.items.concat([prompt('Enter some text')]);
    this.setState({items: newItems});
  },
  handleRemove: function(i) {
    var newItems = this.state.items;
    newItems.splice(i, 1)
    this.setState({items: newItems});
  },
  render: function() {
    var items = this.state.items.map(function(item, i) {
      return (
        <TodoItem item={item} key={item} onClick={this.handleRemove.bind(this,     i)}/>
      );
    }.bind(this));
    return (
      <div>
        <div><button onClick={this.handleAdd}>Add new</button></div>
        <ReactCSSTransitionGroup transitionName="example">
          {items}
        </ReactCSSTransitionGroup>
      </div>
    );
  }
});

React.render(<TodoList/>, document.getElementById('list'));
knowbody
  • 8,106
  • 6
  • 45
  • 70
Chipe
  • 4,641
  • 10
  • 36
  • 64

1 Answers1

2

Your issue is your appending to your todo list. If you add to the front, the resulting animation is what you are looking for.

Change the handleAdd to:

handleAdd: function() {
  var newItems = this.state.items;
  newItems.unshift([prompt('Enter some text')]);
  this.setState({items: newItems});
},

the key point is to use unshift instead of push. Browse the mdn docs to understand the differences

knowbody
  • 8,106
  • 6
  • 45
  • 70
enjoylife
  • 3,801
  • 1
  • 24
  • 33
  • 1
    I do this and the array is added as you want it at the beginning but the transition still happens at the last item as in if you have `['1', '2', '3']` and you `unshift('0')` it will add at the start the `0` but the `3` is the one that will have the transition effect, always. – Johhan Santana Jun 22 '17 at 00:23