React.addons provides CSSTransitionGroup for easily implementing basic CSS animations and transitions.
In this video we're going to take a look at React's add on CSS Transition Group, which is a really easy way to add some animation to your React application. I've got a really basic application here on the left. It's called Slides. In our initial state we return current slide set to zero and then this array of slide objects.
The next slide just sends us back to the first slide if we get past the end. In our render we figure out which one is the current slide and render out this very basic HTML. You can see it here on the right. When we get to the end it goes back to the beginning.
Now what I want to do is animate those slides. The first thing I'm going to do is bring in the CSS transition group. I'm just going to assign that to a variable called CTG. Then down here in my rendered output I'm going to wrap that in the CTG tag.
Here in the CTG tag I'm going to set a transition name. We're going to call that slide. This is going to tie directly to a CSS class. Over here under CSS we're going to create a few classes. The first one is going to be slide enter. This is going to be very, very familiar to anyone whose done any work with ngAnimate. This is heavily inspired by ngAnimate.
We've got slide interactive now. Enter is going to be where our component first enters the DOM before it's actually been animated. Here we're going to have these slide in from the top. I'm going to say top is minus 200 pixels. I'm going to add a transition of half a second.
On our interactive we're going to get that where we want it to be, so I'm going to say top five pixels. When we want to leave we're going to use slide-leave. Again, this is tied to that transition name. Whatever we set the transition name to be is going to be right here before the dash, dash-leave, dash-enter, and so on.
We're going to start at our interactive position, and then we're going to add slide leave active. We're going to slide this out to the bottom. On our leave we're going to add in our transition. When we actually exit we're going to set our opacity to zero.
Let's take a look at this really quick. This actually isn't going to work, but I just want to show you this really quick. It has not taken affect. The reason is that when you're using CSS Transition Group, whether you're animating a single item or an array of items or whatever it is, your component has to have a key. I'm going to give this a key. I'm just going to say map.random and save that, reload. Now we've got our animation.