Animations In ReactNative

Introduction

Every app needs Animation. It makes a mobile app visually appealing. It not only makes the app cool for the users but also enhances their experience. From Onboarding screens to laying out the Components on the screen, it is used almost everywhere in the app.

In this tutorial, we will briefly discuss the Animated API in ReactNative. We will create a component that utilizes the Animated API of ReactNative to animate an image view in the ReactNative app.

About Animated Library

Animated module of the ReactNative provides developers an easy way to add smooth animations to the React Native app. Animated API can animate the built-in components like View, Text, ScrollView, Flat List, and Section List in a performant way. It also allows us to create our Animation using the CreateAnimatedComponent() method.

Example

We will create an animation where we change the size of the image from 1x to 1.4x and then will make it resize from 1.4x to 1x over a few seconds.

Code

import React, { useState, useEffect } from 'react';
import { View, StyleSheet, Animated, Easing } from 'react-native';
const AnimateImage = (props) => {
const [scaleValue] = useState(new Animated.Value(1))
const animateImage = () => {
Animated.sequence([
Animated.timing(scaleValue, {
toValue: 1.4,
duration: 1500,
useNativeDriver: true,
easing: Easing.linear
}),
Animated.timing(scaleValue, {
toValue: 1,
duration: 1500,
useNativeDriver: true,
easing: Easing.linear
})
]).start(() => animateImage());
};
React.useEffect(() => {
animateImage();
}, []);
return (
<View style={{alignItems:'center'}}>
<Animated.Image
source={require('../assets/raw_images/undraw_start_building.png')}
style={[styles.pic, {
transform: [
{
scale: scaleValue
}
]
}]}
/>
</View>
);
}
export default () => <AnimateImage/>
const styles = StyleSheet.create({
pic: {
height: 160,
width: 180,
}
});

Explanation

In the above code snippet, we use the Animated API to animate an image that is in the asset directory. Animated provides a sequence() method that builds the composition of two animations. These animations will be executed sequentially(one after the other).

The first timing() method manages the Scale Value from the state with a duration of 1.5 seconds in an Easing manner. It also changes the value from 1 to 1.4x. The second timing() method makes the scale value of the image from 1.4x to 1x.

We are also using a callback function animateImage() to perform the Image Animation in the loop.

Summary

In this tutorial, we learned the following things-

  • Discussed the Animated API.
  • Implemented the animation code using the Animated API.