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

Reloading UITableView while Animating Scroll in iOS 11

Reloading UITableView while Animating Scroll Calling  reloadData  on  UITableView  may not be the most efficient way to update your cells, but sometimes it’s easier to ensure the data you are storing is in sync with what your  UITableView  is showing. In iOS 10  reloadData  could be called at any time and it would not affect the scrolling UI of  UITableView . However, in iOS 11 calling  reloadData  while your  UITableView  is animating scrolling causes the  UITableView  to stop its scroll animation and not complete. We noticed this is only true for scroll animations triggered via one of the  UITableView  methods (such as  scrollToRow(at:at:animated:) ) and not for scroll animations caused by user interaction. This can be an issue when server responses trigger a  reloadData  call since they can happen at any moment, possibly when scroll animation is occurring. Example of s...

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...

Xcode & Instruments: Measuring Launch time, CPU Usage, Memory Leaks, Energy Impact and Frame Rate

When you’re developing applications for modern mobile devices, it’s vital that you consider the performance footprint that it has on older devices and in less than ideal network conditions. Fortunately Apple provides several powerful tools that enable Engineers to measure, investigate and understand the different performance characteristics of an application running on an iOS device. Recently I spent some time with these tools working to better understand the performance characteristics of an eCommerce application and finding ways that we can optimise the experience for our users. We realised that applications that are increasingly performance intensive, consume excessive amounts of memory, drain battery life and feel uncomfortably slow are less likely to retain users. With the release of iOS 12.0 it’s easier than ever for users to find applications that are consuming the most of their device’s finite amount of resources. Users can now make informed decisions abou...