How to Start and Stop Animations in React Native
In the previous tutorials of react native animation series, we discussed how different types of animations are created in react native. In this blog post, let’s see how to start and stop animations in react native.
Sometimes, even though we define a specific time for animation we may need it to get stopped to enhance the user experience. start() and stop() are the methods used to initiate an animation and to end an animation.
Animated.timing(startValue, {
toValue: endValue,
duration: duration,
useNativeDriver: true,
}).start();
setTimeout(() => {
Animated.timing(startValue, {
toValue: endValue,
duration: duration,
useNativeDriver: true,
}).stop();
}, 2000);
Here, Animated.timing() and start() are used to create an animation and the duration of the animation is given 10,000 ms, ie ten seconds. But the Animation is halted after 2000 ms, ie two seconds, by using setTimeout and stop().
Here’s the full react native example to start and stop animations.
import React, {useEffect, useRef} from 'react';
import {View, Animated, StyleSheet} from 'react-native';
const MoveY = () => {
const startValue = useRef(new Animated.Value(1)).current;
const endValue = 150;
const duration = 8000;
useEffect(() => {
Animated.timing(startValue, {
toValue: endValue,
duration: duration,
useNativeDriver: true,
}).start();
setTimeout(() => {
Animated.timing(startValue, {
toValue: endValue,
duration: duration,
useNativeDriver: true,
}).stop();
}, 2000);
}, [startValue]);
return (
<View style={styles.container}>
<Animated.View
style={[
styles.square,
{
translateY: startValue,
},
]}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
square: {
height: 50,
width: 50,
backgroundColor: 'red',
},
});
export default MoveY;
Following is the output of the example.
You can get the source code of all my animation examples given in this tutorial series from this Github repository.