Skip to main content

React Native Animation

React Native Animations provide an extra effect and great user experience in the app. Animations convey physically believable motion in your interface.
There are two types of complementary animation systems in React Native. These are:
  • Animated: The Animated API is used to interactive control the specific values. It focuses on declarative relationships between inputs and outputs. It has a start and stop methods to control the time-based animation execution.
  • Animated exports four different animated components as View, Text, Image and ScrollView. We can also create our own animated component using Animated.createAnimatedComponent().
  • LayoutAnimated: The LayoutAnimated is used to animate the global layout transactions.
  • Animated Methods

    MethodsDescription
    Animated.timing()It animates a value over time using various easing curve, or by using own function.
    Animated.event()It maps event directly to animated values.
    Animated.spring()It animate the valueIt tracks the velocity of state to create fluid motion as toValue updates.
    Animated.decay()It starts the animations with initial velocity and gradually goes slows to stop.

    React Native Animation Example 1 (Animated.timing())

    In this example, we will create a spinning animation on image using Animated.timing().

    App.js

    1. import React, { Component } from 'react';  
    2. import {StyleSheet, AppRegistry,Text, View,Animated,Easing} from 'react-native';  
    3.   
    4. export default class DisplayAnImage extends Component {  
    5.     constructor () {  
    6.         super()  
    7.         this.spinValue = new Animated.Value(0)//declare spinValue as a new Animated.Value and pass 0 (zero) in it.  
    8.     }  
    9.     componentDidMount () {  
    10.         this.spin()  
    11.     }  
    12.     //create a spin method and call it from componentDidMount  
    13.     spin () {  
    14.         this.spinValue.setValue(0) //set spinValue to 0 (zero)  
    15.         Animated.timing(    //calling Animated.timing() method, it takes two arguments:  
    16.             this.spinValue, // value  
    17.             {           // and config object  
    18.                 toValue: 1, //and setting spinValue to 1  
    19.                 duration: 4000, //within 4000 milliseconds  
    20.                 easing: Easing.linear  
    21.             }  
    22.         ).start(() => this.spin())  
    23.     }  
    24.     render () {  
    25.         const spin = this.spinValue.interpolate({  
    26.             inputRange: [0, 1],  
    27.             outputRange: ['0deg', '360deg']  
    28.         })  
    29.         return (  
    30.             <View style={styles.container}>  
    31.                 <Animated.Image  
    32.                     style={{  
    33.                         width: 227,  
    34.                         height: 200,  
    35.                         transform: [{rotate: spin}] }}  
    36.                     source={require('MyReactNativeApp/img/react-logo.png')}  
    37.                 />  
    38.             </View>  
    39.         )  
    40.     }  
    41. }  
    42. const styles = StyleSheet.create({  
    43.     container: {  
    44.         flex: 1,  
    45.         justifyContent: 'center',  
    46.         alignItems: 'center'  
    47.     }  
    48. })  
    49. // skip this line if you are using Create React Native App  
    50.   
    51. AppRegistry.registerComponent('DisplayAnImage', () => DisplayAnImage);  
    The interpolate() method call any Animated.Value. It interpolates the value before updating the property. In above example, we map 0 (zero) degrees to 360 degrees.
    We pass an inputRange [0,1] and get the outputRange['0deg', '360deg'] array.

    Output:

    React Native Animation

    React Native Animation Example 2 (Animated.timing())

    In this example, we declare a single animated value this.aninatedValue and use it with interpolate to create multiple animations, such as: marginLeft, opacity, fontSize, and rotate. We will interpolate these properties for styling such as opacity, margins, text sizes, and rotation properties.

    App.js

    1. import React, { Component } from 'react';  
    2. import {StyleSheet, AppRegistry,Text, View,Animated,Easing} from 'react-native';  
    3.   
    4. export default class DisplayAnImage extends Component {  
    5.     constructor () {  
    6.         super()  
    7.         this.animatedValue = new Animated.Value(0)  
    8.     }  
    9.     componentDidMount () {  
    10.         this.animate()  
    11.     }//animate method is call from componentDidMount  
    12.     animate () {  
    13.         this.animatedValue.setValue(0)  
    14.         Animated.timing(  
    15.             this.animatedValue,  
    16.             {  
    17.                 toValue: 1,  
    18.                 duration: 2000,  
    19.                 easing: Easing.linear  
    20.             }  
    21.         ).start(() => this.animate())  
    22.     }  
    23.   
    24.     render() {  
    25.         const marginLeft = this.animatedValue.interpolate({  
    26.             inputRange: [0, 1],  
    27.             outputRange: [0, 300]  
    28.         })  
    29.         const opacity = this.animatedValue.interpolate({  
    30.             inputRange: [0, 0.5, 1],  
    31.             outputRange: [0, 1, 0]  
    32.         })  
    33.         const movingMargin = this.animatedValue.interpolate({  
    34.             inputRange: [0, 0.5, 1],  
    35.             outputRange: [0, 300, 0]  
    36.         })  
    37.         const textSize = this.animatedValue.interpolate({  
    38.             inputRange: [0, 0.5, 1],  
    39.             outputRange: [18, 32, 18]  
    40.         })  
    41.         const rotateX = this.animatedValue.interpolate({  
    42.             inputRange: [0, 0.5, 1],  
    43.             outputRange: ['0deg', '180deg', '0deg']  
    44.         })  
    45.   
    46.   
    47.         return (  
    48.             <View style={styles.container}>  
    49.                 <Animated.View //returns Animated.View  
    50.                     style={{  
    51.                         marginLeft,  
    52.                         height: 30,  
    53.                         width: 40,  
    54.                         backgroundColor: 'red'}} />  
    55.                 <Animated.View  
    56.                     style={{  
    57.                         opacity,  
    58.                         marginTop: 10,  
    59.                         height: 30,  
    60.                         width: 40,  
    61.                         backgroundColor: 'blue'}} />  
    62.                 <Animated.View  
    63.                     style={{  
    64.                         marginLeft: movingMargin,  
    65.                         marginTop: 10,  
    66.                         height: 30,  
    67.                         width: 40,  
    68.                         backgroundColor: 'orange'}} />  
    69.                 <Animated.Text // returns Animated.Text  
    70.                     style={{  
    71.                         fontSize: textSize,  
    72.                         marginTop: 10,  
    73.                         color: 'green'}} >  
    74.                     Animated Text!  
    75.                 </Animated.Text>  
    76.                 <Animated.View   
    77.                     style={{  
    78.                         transform: [{rotateX}],  
    79.                         marginTop: 50,  
    80.                         height: 30,  
    81.                         width: 40,  
    82.                         backgroundColor: 'black'}}>  
    83.                     <Text style={{color: 'white'}}>Hello from TransformX</Text>  
    84.                 </Animated.View>  
    85.             </View>  
    86.         )  
    87.     }  
    88. }  
    89. const styles = StyleSheet.create({  
    90.     container: {  
    91.         flex: 1,  
    92.         paddingTop: 150  
    93.     }  
    94. })   
    95. // skip this line if you are using Create React Native App  
    96. AppRegistry.registerComponent('DisplayAnImage', () => DisplayAnImage);  


    Output:

    React Native Animation

    LayoutAnimation API

    LayoutAnimation allow to globally configure, create, and update animations. This will be used for all views in the next render/layout cycle.
    The LayoutAnimation is quite useful, it has much less control than Animated and other animation libraries.

    To use this API in Android we need to set the following flags via UIManager:

    1. UIManager.setLayoutAnimationEnabledExperimental &&  
    2.   UIManager.setLayoutAnimationEnabledExperimental(true);  

    React Native LayoutAnimation Example

    In this example, we create a TouchableOpacity and a View component. On pressing the TouchableOpacity component calls the _onPress() method and it animates the View component by increases width and height of View by 15 unit.

    1. import React from 'react';  
    2. import {  
    3.     NativeModules,  
    4.     LayoutAnimation,  
    5.     Text,  
    6.     TouchableOpacity,  
    7.     StyleSheet,  
    8.     View,  
    9. } from 'react-native';  
    10.   
    11. const { UIManager } = NativeModules;  
    12.   
    13. UIManager.setLayoutAnimationEnabledExperimental &&  
    14. UIManager.setLayoutAnimationEnabledExperimental(true);  
    15.   
    16. export default class App extends React.Component {  
    17.     state = {  
    18.         w: 100,  
    19.         h: 100,  
    20.     };  
    21.   
    22.     _onPress = () => {  
    23.         // Animate the update  
    24.         LayoutAnimation.spring();  
    25.         this.setState({w: this.state.w + 15, h: this.state.h + 15})  
    26.     }  
    27.   
    28.     render() {  
    29.         return (  
    30.             <View style={styles.container}>  
    31.                 <View style={[styles.box, {width: this.state.w, height: this.state.h}]} />  
    32.                 <TouchableOpacity onPress={this._onPress}>  
    33.                     <View style={styles.button}>  
    34.                         <Text style={styles.buttonText}>Press me!</Text>  
    35.                     </View>  
    36.                 </TouchableOpacity>  
    37.             </View>  
    38.         );  
    39.     }  
    40. }  
    41.   
    42. const styles = StyleSheet.create({  
    43.     container: {  
    44.         flex: 1,  
    45.         alignItems: 'center',  
    46.         justifyContent: 'center',  
    47.     },  
    48.     box: {  
    49.         width: 200,  
    50.         height: 200,  
    51.         backgroundColor: 'blue',  
    52.     },  
    53.     button: {  
    54.         backgroundColor: 'green',  
    55.         paddingHorizontal: 20,  
    56.         paddingVertical: 15,  
    57.         marginTop: 15,  
    58.     },  
    59.     buttonText: {  
    60.         color: '#fff',  
    61.         fontWeight: 'bold',  
    62.     },  
    63. });  


    Output:

    React Native Animation React Native Animation

Comments

Popular Posts

Master Map & Filter, Javascript’s Most Powerful Array Functions

Master Map & Filter, Javascript’s Most Powerful Array Functions Learn how Array.map and Array.filter work by writing them yourself This article is for those who have written a  for  loop before, but don’t quite understand how  Array.map  or  Array.filter  work. You should also be able to write a basic function. By the end of this, you’ll have a complete understanding of both functions, because you’ll have seen how they’re written. Array.map Array.map  is meant to transform one array into another by performing some operation on each of its values. The original array is left untouched and the function returns a new, transformed array. For example, say we have an array of numbers and we want to  multiply each number by three . We also don’t want to change the original array. To do this without  Array.map , we can use a standard for-loop. for-loop var originalArr = [1, 2, 3, 4, 5]; var newArr = []; for(var i = 0; i < originalArr.length; i+...

Integrate the FaceID or TouchID Authentication in iOS Apps - Swift

FaceID or TouchID Authentication Dear Folks, today I am going to explain the proper way to integrate the Face ID or Touch ID in iOS App. Face ID and Touch ID are secure, familiar authentication methods that people trust. Follow below steps: Step 1: Add NSFaceIDUsageDescription Key in info.plist file <key>NSFaceIDUsageDescription</key> <string>This app requires Face ID permission to authenticate using Face recognition.</string> Step 2: Create a swift file with any name but it would be better to related to its functionality, Like BioMetrixFile.swift Step 3: In BioMetrixFile write below codes and follow instructions. But before proceeding further import LocalAuthentication class in BioMetrixFile. Now, create typealias for success or failure blocks to well manage Authentication Success or Failure. public typealias AuthenticationSuccess = (() -> ()) public typealias AuthenticationFailure = ((AuthenticationError) -> ()) Now written all s...

React Native: How To Open App Settings Page

  React Native: How To Open App Settings Page React Native has a Linking module to manage the interaction with other applications in the device. In this article, I will explain how you can open “Application Setting Page” of the device using. Sample Case Before I explain how to do this, I’ll talk about an example case where we might need this: You need to get location permission within the application from a user using an iOS operating system and you asked for permission. But user did not agree to grant this permission the first time. In this case, you cannot ask your user for location permission the second time. In this case, the only thing to do is to direct the user to the settings page of our application and make it manually allow it. Now that we have explained our example situation, we can move on to how we can redirect our user to the “settings page of our application”. Open App Settings Page iOS If our user is using an iOS operating system, we can handle the whole process wit...