This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Stagger React Native Animations with Animated.stagger

2:53 React lesson by

In this lesson we'll use Animated.stagger to stagger Animated.timing animations that animate the height of a React Native view every 300 milliseconds.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

In this lesson we'll use Animated.stagger to stagger Animated.timing animations that animate the height of a React Native view every 300 milliseconds.

We'll start by importing Animated and Dimensions from React Native. We'll do const, height, and destructure that from our Dimensions.get, which is a function call which takes window, which will return the dimensions of our current orientation.

Next, we'll create a componentWillMount lifecycle method and we'll create three animated values. We'll call them, this.animatedValue1 = Animated.Value, and passing zero as the default. this.animatedValue2, and passing zero as the default, and this.animatedValue3 and pass in zero as the default as well.

Next, we'll need to set up our styles, so we'll create animatedStyle1, which is an object and we'll animate the height, and then we'll pass in this.animatedValue1 to the same for our second one, animatedStyle2, object, height, this.animatedValue2. Finally, our third in style 3, then we'll go to the height, this.animatedValue3.

Next, we'll need to switch our regular views to animated views, so that our animations will work. We'll apply our styles that we just created, so pass in animatedStyle1, animatedStyle2, and then our third animation animatedStyle3.

Currently, we have our box height set to 50, so we'll go ahead and remove that. Because our defaults are zero and we're animating the height, when we refresh our emulator, our boxes will disappear because our heights are set to zero.

We'll create a componentDidMount lifecycle method, which will call Animated.stagger, which is a function that the first argument takes, is the milliseconds to stagger each animation. We'll say 300 milliseconds. The second is an array of animations. We'll do Animated.timings, which takes this.animatedValue1 to the height of our current display over the course of 1,500 milliseconds.

We'll do that for each of our animations, so we'll change this.animatedValue1 to 2, and this one to 3. Now, when I call start on our stagger and refresh, you can see that the heights are animated but are staggered 300 milliseconds apart.

Animated.stagger does not care about the animations that you have. We can change our second animation to animate over the course of 3,000 milliseconds. Rather than animate to the height of our entire container, we can say animate to 500, but do it very quickly over the course of 400 milliseconds. Now, when we refresh, each animation does its own thing but is still staggered every 300 milliseconds.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?