Explain Animations in React Native
Animations in React Native: React Native has an Animated API that handles animations in the app. It has various functions to create most types of animation(E.g Fading, color change, width and Height change, position change). We will mostly be using Animated.parallel, Animated.timing, Animated.value, and Animated.View this example.
Implementation: Now let’s start with the implementation:
Step 1: Open your terminal and install expo-cli by the following command.
npm install -g expo-cli
Step 2: Now create a project by the following command.
expo init animationDemo
Step 3: Now go into your project folder i.e. animationDemo
Project Structure: It will look like the following.
Steps to Create Animation:
- Defining State: We will import Animated from ‘react-native’.Then we will declare our state that will be later changed by the animate function. In this, we are using “right” which will shift the <Animated.View> from left-to-right and vice-versa. And “radius” state which will change borderRadius of the View during animation.
- Defining Animation functions: We will define two functions leftToRight and rightToLeft which will animate the View when called. In this, we are using Animated.parallel() function which is used to run multiple animations simultaneously. And Animated.timing() function which takes state, duration of the animation, final value as parameter. The Start() for starting the animation.
- Creating the View: Now we will create a View using <Animated.View> and in style pass the animation state.
Note: Use <Animated.View> for creating a View that will animate based on animated state.Normal <View> will throw Stack limit exceeded error.
Start the server by using the following command.
npm run android
Interpolation: Let’s suppose we want to use “%” instead of a number for defining our right style property.If we pass “%” as in <Animated.View> and try to change it in our Animated.timing() function we will get an error. This is where interpolation helps.It maps input ranges to output ranges(E.g. 0-100 into 0%-100%).We just have to apply interpolation in <Animated.View> right style prop and the rest of the code will be the same.