In this lesson we will use Animated.spring and TouchableWithoutFeedback to animate the scale of a button in our React Native application. We will use the scale transform property and see how adjusting the friction of a spring will effect the spring animation.
[00:00] We'll start by importing TouchableWithoutFeedback, and Animated from the React Native module.
[00:08] Next, let's go over application. We can see that we have a styles.container assigned to our container style, a button, and some text that says, "Press me."
[00:18] We can review the styles here, and see that the Flex1 is applied to the container, to take up all available space. We're centering our items, we have a button with a background color of grey, a width and height of 150, centering its items which is text, which has the color of white.
[00:33] Now, we'll wrap our button with a TouchableWithoutFeedback. This will easily allow us to register touches from the UI.
[00:43] Now, we'll create two functions to handle our press animation. The first one will be handlePressIn, and the second will be handlePressOut.
[00:52] To make sure these have the proper this scope, we need to create a constructor called "super," with our props, and then, bind this.handlePressIn to the this scope, and then this.handlePressOut to the this scope, as well. Now, we'll go add those as properties to our TouchableWithoutFeedback.
[01:19] The properties are on PressIn, we'll pass it on this.handlePressIn, and on PressOut. We'll pass that on handlePressOut.
[01:29] Now, we'll create our componentWillMount function, which we'll use to create this.animatedvalue, and assign it a new animated.value with a default value of 1.
[01:41] Next thing we'll need to do is create our animated style. this.animatedstyle is equal to an object, and we're going to add the style transform, and transform takes an array of styles, animate, and we'll say scale this.animatedvalue.
[01:56] We need to apply this to an animated view, we'll change our view to an Animated.View so that it can use animated values. We'll add our style here to the animated view by passing in an array instead, and adding in our animated style.
[02:15] In our press in, we'll use animated.spring which is a function that takes in animatedvalue as the first parameter, as well as a to value to animate to, we'll say animate to .5, and then, we'll call start on our animation.
[02:33] Now, when we refresh our emulator and we PressIn, we can see that we animated to .5, but on our release, nothing happens.
[02:41] Now, we go to our press out, and call animated.spring, as well, pass in on this.animatedvalue, and animate back to value, back to 1. The default friction is 7, however, we'll set ours to 3.
[02:57] The default tension is 40, and we'd leave that as is. Now, we''ll call start on our animation, we'll refresh our emulator, PressIn, which will animate to .5, and release, and see a nice spring action on the PressOut.