We'll start by importing animated and easing from React Native. Let's walk through our application.
We have a view, with a styles.container, and the nested child view with styles.box.
You can see our styles here. We have flex1 on the container. We just take up all available space, and center our nested items -- which is our box -- which has a background-color of 3s, and a width and height of 100.
Now let's add a componentWillMount() lifecycle method. We'll then create an instance variable called this.animatedvalue, and assign it a new instance of Animated.Value, which takes a default value, which we'll pass in as 1.
Now, we'll create an animated style variable, which will be our inline style, which will be an object with an opacity key. We'll pass in this.animatedvalue, which is our animated value instance.
In order to use animated styles, we need to change our view to an Animated.View. To pass in multiple styles to a particular view, we simply pass in an array.
We'll pass in our styles.box inside of the array, and then also the animated style that we created.
If we refresh our emulator, we can still see that the opacity of the box is 1. Let's animate by creating a componentDidMount() lifecycle method. We'll then use Animated.timing, which is a function that takes two arguments.
The first is the animated instance that we want to animate, in our case this.animatedvalue, and also a configuration object that takes a few different parameters.
The first is 2 value, which is the value we want to animate to. In our case, we want to animate to .3 opacity.
The second is duration. The duration is in milliseconds, and so we'll animate over 1,000 milliseconds.
Finally, to start animation, we need to call .start on the animated timing.
Now, when we refresh our emulator, we can see that we animated the opacity from 1 to .3 over 1,000 milliseconds.
Another property that the configuration object takes is a parameter called easing. This will take a function, which React Native provides many easing functions out of the box.
We'll use our easing input, and pass in the bounce easing. Now, I'm going to refresh our emulator. We can see that the opacity fluctuated over the period of time.
To make it a little more apparent, let's change our duration from 1,000 to 3,000.
Animated is not only capable of animating opacity, but it's capable of animating any style. We'll change our starting value to 100. We'll change our "to" value to 150, and we'll change, instead of opacity, we'll change our style that we want to animate to height.
Now, when we refresh our emulator, we can see that it bounced over the course of three seconds. Let's switch this back to 1,000, refresh, and get and get a cool effect.
There are many easing functions that you can choose to accomplish the desired animation in your application. You can find them in the documentation on the React Native website.