React Native Interpolation Example
React Native animation tutorials cannot be completed without learning interpolation. Interpolation helps you to create good animations by mapping input ranges to output ranges. It gives you fine control over what output should be attained when a specific input value is fed.
For example, this is how you use the interpolate method.
value.interpolate({
inputRange: [0, 50, 100],
outputRange: [0, 0.75, 1],
});
What this means is when the input value is 0, then the output is also 0. But when the input reaches value 50, the output value becomes 0.75. And when the input value is 100 and the output reaches 1.
For more understanding, let’s take a react native animation example where a square view moves across the y-axis and the opacity of the square also changes. What we do is the values of opacity are mapped to the values of the movement of the square using interpolation.
First, we declare values of the opacity using state.
const startValue = useRef(new Animated.Value(0)).current;
const endValue = 1;
const duration = 5000;
We use Animated.timing() method to initiate the Animation.
Animated.timing(startValue, {
toValue: endValue,
duration: duration,
useNativeDriver: true,
}).start();
Next is to interpolate values so that the input range of the opacity is mapped to the input range of the transform.
<Animated.View
style={[
styles.square,
{
opacity: startValue,
transform: [
{
translateY: startValue.interpolate({
inputRange: [0, 1],
outputRange: [150, 0], // 0 : 150, 0.5 : 75, 1 : 0
extrapolate: 'clamp',
}),
},
],
},
]}
/>
When the opacity is 0, the Y coordinate value will be 150. When the opacity becomes 1, the Y coordinate would become 0.
Following is the full animation example of react native interpolation.
import React, {useEffect, useRef} from 'react';
import {View, Animated, StyleSheet} from 'react-native';
const FadeIn = () => {
const startValue = useRef(new Animated.Value(0)).current;
const endValue = 1;
const duration = 5000;
useEffect(() => {
Animated.timing(startValue, {
toValue: endValue,
duration: duration,
useNativeDriver: true,
}).start();
}, [startValue]);
return (
<View style={styles.container}>
<Animated.View
style={[
styles.square,
{
opacity: startValue,
transform: [
{
translateY: startValue.interpolate({
inputRange: [0, 1],
outputRange: [150, 0], // 0 : 150, 0.5 : 75, 1 : 0
extrapolate: 'clamp',
}),
},
],
},
]}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
alignItems: 'center',
flex: 1,
},
square: {
height: 50,
width: 50,
backgroundColor: 'green',
},
});
export default FadeIn;
And here’s the output:
The interpolate method can also be used in rotating animations.
You can get the source code of all my animation examples given in this tutorial series from this Github repository.