Reputation: 827
I have a react component, which uses ReactCSSTransitionGroup for CSS transitions and I've got my server up and running with a dummy database and an API call that returns an array of objects and then for testing purposes, I use setTimeout to query my api url:
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
var ItemsList = React.createClass({
getInitialState: function() {
return {
items: [],
api: {
getItems: '/api/items'
}
}
},
componentDidMount: function() {
this.fetchData();
},
fetchData: function() {
$.get(this.state.api.getItems, function(data) {
this.setState({
items: data
});
setTimeout(this.fetchData, 3000);
}.bind(this));
},
render: function() {
var items = this.state.items.map(function(item, index) {
return (
<div className="title" key={index}>
{item.title}
</div>
);
}.bind(this));
return (
<div className="content">
<ReactCSSTransitionGroup transitionName="example">
{items}
</ReactCSSTransitionGroup>
</div>
);
}
});
React.render(
<ItemsList />,
document.querySelector('.react')
);
And here's the CSS:
.example-enter {
opacity: 0.01;
}
.example-enter.example-enter-active {
opacity: 1;
transition: opacity 2.5s ease-in;
}
.example-leave {
opacity: 1;
}
.example-leave.example-leave-active {
opacity: 0.01;
transition: opacity 2.5s ease-in;
}
What I want to achieve is that every single time an item is added to an array, I want it to animate in, BUT with one condition - new item has to appear at the top of the list.
So I do orderBy created_at DESC
in PHP and it returns all the objects successfully (in the order that I want), but React.js renders the new object at the top and then animates the very last element (even though it added a new one at the top).
What am I doing wrong? :(
Upvotes: 3
Views: 3819
Reputation: 827
Figured it out!
I had to do
<div className="title" key={item.id}>
{item.title}
</div>
instead of:
<div className="title" key={index}>
{item.title}
</div>
Because index
comes from an array and it changes everytime an element is added.
Upvotes: 7