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: [01],  
    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: [01],  
    27.             outputRange: [0300]  
    28.         })  
    29.         const opacity = this.animatedValue.interpolate({  
    30.             inputRange: [00.51],  
    31.             outputRange: [010]  
    32.         })  
    33.         const movingMargin = this.animatedValue.interpolate({  
    34.             inputRange: [00.51],  
    35.             outputRange: [03000]  
    36.         })  
    37.         const textSize = this.animatedValue.interpolate({  
    38.             inputRange: [00.51],  
    39.             outputRange: [183218]  
    40.         })  
    41.         const rotateX = this.animatedValue.interpolate({  
    42.             inputRange: [00.51],  
    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

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...

16 AWS Gotchas

16 AWS Gotchas In January I launched the MVP for my own startup,  Proximistyle , which helps you find what you’re looking for nearby. On advice from friends and industry contacts I chose AWS as my cloud provider. Having never had to set up my own cloud infrastructure before, the learning curve to get from no experience to a stable VPC system I was happy with was significantly steeper than expected, and had its fair share of surprises. #1 Take advantage of the free resources offered AWS offers a free tier for new accounts. If you have recently bought a domain and set up a company you qualify for the free tier for a year. Additionally, if you are a bootstrapped startup you can apply for  the Startup Builders package  and get $1000 in AWS credits. After doing the above, you’re now ready to get started with setting up the AWS infrastructure for your startup. #2 Set up billing budgets and alerting The very first thing you should do after setting up billing, is enabling a budge...

Ultimate Folder Structure For Your React Native Project

  Ultimate Folder Structure For Your React Native Project React native project structure React Native is a flexible framework, giving developers the freedom to choose their code structure. However, this can be a double-edged sword for beginners. Though it offers ease of coding, it can soon become challenging to manage as your project expands. Thus, a structured folder system can be beneficial in many ways like better organization, simplified module management, adhering to coding practices, and giving a professional touch to your project. This write-up discusses a version of a folder arrangement that I employ in my React Native projects. This structure is based on best practices and can be modified to suit the specific needs of your project. Before we get into the project structure let’s give credit to @sanjay who has the original idea of the structure but I modify his version of the code, to make it better. Base library axios  — For network calling. react-navigation ...