In this video, we're going to talk about "TransitionSpring," which is a component available to us in react-motion. We're going to take a look at how it differs from a regular spring. I've built up a very simple application here. In my state, I've got a key of items. That is an array running from zero to three.
I've also got a key of current count that keeps track of the last value available in our items. Here in our "handleAdd," we're simply adding a new item and making sure it has a unique value by continually increasing the current count. "handleRemove" removes one of those items from our state.
Then we've got our standard "Git defaults," "Git ends" for our spring. You'll notice, in fact I am, at this point, using a spring. When I load up the application, I'm getting my initial animation. The idea is that I can click on any of these boxes to remove them. I should be able to click on this "add box" button to add a new one.
At the moment, the "Remove" kind of works, but I certainly don't have any animation. As soon as I try to add anything, the entire application breaks down. This is because a spring is animating things that are already in the scope of our application, whereas a "TransitionSpring" is meant to animate mounting and unmounting of new components.
The first thing I'm going to do is switch from a spring to a "TransitionSpring." We'll go ahead and update that in our component as well, here and at the end. Go ahead and save that. Right away, I can see that my "add box" function now works. I can remove and I can add, but I'm still not getting any animation on the removal or the adding of a box.
To deal with that, "TransitionSpring" comes with two additional methods that we can access. The first one is going to be "willEnter" and the second one is "willLeave." We're going to set those up here, "willEnter," and this meth, "willLeave." We'll create those methods here in our component.
" willLeave" will act as our transition from our end value, which is essentially our current value when something is going to leave to a new value, so return a new object. This is going to match the shape of our default values as well as our end values.
We're going to have a val. We've got a width of zero, capacity of zero, and a scale of zero. Again, this is our component leaving our application. We're going to copy this for our "willEnter." This essentially acts as our default value for our newly added components. Now, when we remove an item, we can see its scale and width is affected. As we add an item, it is also animating in.