One of the best way to improve user experience in mobile application is to use animation. In Android and iOS native development, animation is handled differently. Also, not all animations available in Android can be implemented in iOS and vice versa. React Native Animation provides following two APIs to implement animation in both Android and iOS :
- Animated API
- LayoutAnimation API
If you have not read previous articles in this series, we request you to do so-
Tutorial Index
- Tutorial #1 â React Native â Introduction
- Tutorial #2 â React Native Props and State
- Tutorial #3 â Styling React Native App
- Tutorial #4 â React Native UI Components
- Tutorial #5 â React Native API Integration
- Tutorial #6 â React Native Animation
- Tutorial #7 â Top 10 React Native libraries
In this tutorial, we will learn how to use these APIs with examples .
Animated API :
We can use the animated API with View, Text, ScrollView, Image, FlatList and SectionList. We can also use Animated.createAnimatedComponent() method to create one animated component.
For example :
import * as React from 'react'; import { Text, View, StatusBar, StyleSheet, Animated } from 'react-native'; export default class App extends React.Component { state = { width: new Animated.Value(0), } componentDidMount() { Animated.timing( this.state.width, { toValue: 100, duration: 3000, } ).start(); } render() { return ( xView style={{ paddingTop: 30,paddingLeft : 40 }}x xAnimated.View style = {{backgroundColor: "blue",width: this.state.width, height: 50}}/x x/Viewx ); } }
In this example, it will create one view from âwidthâ â0â to â100â over a duration of 3 seconds. Notice that we are using âAnimated.Viewâ instead of âViewâ. Also, we are using âAnimated.timingâ method to change the value of âwidthâ. âwidthâ is a value defined in the âstateâ of the component. Its value is used to set the width of the âAnimated.Viewâ. Using the same approach, we can animate both height,width of a view, add animation to the opacity of a view etc. This is not same as changing the state continuously. If we change the state continuously, it will re-render the component again and again, which will impact the performance of the view. Animation API uses a different mechanism to show the animation more efficiently.
Animation configuration :
Animated provides three different types of animations :
- Animated.decay() : These types of animations starts with a initial velocity and gradually slows down to a final velocity.
- Animated.spring() : Spring physics model animation .
- Animated.timing() : It animates a value over a period of time. This is one of the most commonly used function of âAnimatedâ.
Animated values :
In the above example, we have used Animated.value. Animated.Value() is used for single values. Other than this method, we also have Animated.ValueXY(). This is used for vectors.
For starting an animation, start() method is used. This method optionally takes one completion handler block that will be called once it completes. We can also call stop() method to stop one animation before it completes with the predefined values. For example, we may need to call stop() on any user interaction or if any other animation starts. We can detect on the completion block if the animation was finished normally or if stop() was called. It gives us one flag called âfinishedâ on the completion block that will be âtrueâ for normal completion and âfalseâ for âstop()â completion.
Combine animations :
We can combine two animated values to create a new one. Following are the methods to combine animations :
- Add : Animated.add()
- Subtract : Animated.subtract()
- Divide : Animated.divide()
- Modulo : Animated.modulo()
- Multiply : Animated.multiply()
Gestures :
If we are working with animation, we may have to deal with gestures. Animated.event() method is used to map gesture events to animated values. Structured map syntax is used for that.
Reading the current animation value :
Sometimes we may need to read the current animation value of a view. But, as I have explained before, this is not like updating the state value continuously. This is mainly done in the native runtime and so, tracking the current value is difficult. Following are the two ways that we can use for that :
- spring.stopAnimation(callback) : It will stop the animation and invoke the callback . This callback will hold the final value.
- spring.addListener(callback) : In this case, callback will be invoked asynchronously. We will get one recent value of the animation with the callback. This is useful if we are processing something based on the current state of the animation.
LayoutAnimation API :
LayoutAnimation doesnât provides much features like Animated API, but it is useful in many cases. Basically, it will animate the views to their new position on next render. This is useful for flexbox layout updates and also if the changes affects any ancestor view. Normally, we use it by changing the values in a state.
On Android, it will work only if we add the below configuration :
UIManager.setLayoutAnimationEnabledExperimental xx
UIManager.setLayoutAnimationEnabledExperimental(true);
Example :
import * as React from 'react'; import { LayoutAnimation, Text, View, StatusBar, StyleSheet, Animated, NativeModules, Button } from 'react-native'; const { UIManager } = NativeModules; UIManager.setLayoutAnimationEnabledExperimental xx UIManager.setLayoutAnimationEnabledExperimental(true); export default class App extends React.Component { state = { width: 0, }; onClickButton = () =x { LayoutAnimation.spring(); this.setState({ width: this.state.width + 100 }); }; render() { return ( xView style={{ paddingTop: 30, paddingLeft: 40 }}x xView style={{ backgroundColor: 'blue', width: this.state.width, height: 50, }} /x xButton onPress={this.onClickButton} title="Click me"/x x/Viewx ); } }
This is the same example as we have seen above. The only difference is that here we are not using any âAnimatedâ views. Also we are not asking to do one animation for an âxâ amount of time. It has one button at the bottom of the animated view. If the user clicks on the button, it increases the width of the button by â100â on each click. It animates the changes for that view. Note that we are only updating the state, not directly changing the view. onClickButton method is called on button click. Inside the âonClickButtonâ method, the below piece of code is doing the magic :
LayoutAnimation.spring();
We are only adding one line of code and that adds the animation to the view. If we have a lot of views, we can store the properties in the state and update the state using âLayoutAnimationâ to animate all views simultaneously.
Both âLayoutAnimationâ and âAnimatedâ apis are useful in an application. It depends on the use cases. âAnimatedâ is pretty strong but it involves writing a lot of code for any types of animation. But it provides more control to the animation. âLayoutAnimationâ is great for doing animation on re-render without writing a lot of code and without changing any views. Just store the view properties in the state and change the state to do the animation.
Conclusion
The article explained how React Native Animation API can be leveraged to develop fabulous application that appeals to masses.
Please feel free to give us your feedback.
Tutorial Index
- Tutorial #1 â React Native â Introduction
- Tutorial #2 â React Native Props and State
- Tutorial #3 â Styling React Native App
- Tutorial #4 â React Native UI Components
- Tutorial #5 â React Native API Integration
- Tutorial #6 â React Native Animation
- Tutorial #7 â Top 10 React Native libraries