React: Rendering a list in reverse order

hedgeday picture hedgeday · May 4, 2015 · Viewed 17.1k times · Source

I'm building an app with React and Reflux, and I am trying to render a list of items in a specific order.

The items are custom Post components that are rendered in reverse chronological order, so the newest post is at the top of the list.

I am using Khan Academy's TimeoutTransitionGroup to have the list items fade in and out.

The problem I'm seeing is that when I add a new post and the component gets the updated list via new props, the transition happens on the last element in the list rather than the first. I would like to have it so that the first element fades in, since that's the position of the new item that was added.


Post 2 <- This post was newly added


Post 1 <- This post fades in


Is there a way to specify the same order of items, but render them in the reverse order, or something similar?

This is my component's render function:

    if (!(this.props.posts && this.props.ordering)) return false;
    var posts = this.props.ordering.map(function(postId, index) {
        return <Post key={index} post={this.props.posts[postId]}/>;
    }, this);
    return (
        <div className="post-collection">
            <TimeoutTransitionGroup 
                enterTimeout={500}
                leaveTimeout={500}  
                transitionName="postTransition">
                {posts}
            </TimeoutTransitionGroup>
        </div>
    );

This is the CSS transition:

.postTransition-enter {
    opacity: 0;
    transition: opacity .25s ease-in;
}

.postTransition-enter.postTransition-enter-active {
    opacity: 1;
}

.postTransition-leave {
    opacity: 1;
    transition: opacity .25s ease-in;
}

.postTransition-leave.postTransition-leave-active {
    opacity: 0;
}

Any help will be much appreciated!

Answer

vkurchatkin picture vkurchatkin · May 4, 2015

You shouldn't use index as key, it defeats the purpose. For example, if you add an item to the beginning of the array, react will detect only one new key - the last one. All other components would be reconciled according to their keys. You should use unique id of a post as a key instead.