Animate Colors with React Native Interpolate

Jason Brown
InstructorJason Brown
Share this video with your friends

Social Share Links

Send Tweet

We'll use the interpolate function from an Animated.Value to transition the background color of an Animated.View. We'll simultaneously translate the position with the same Animated.Value.

[00:00] We'll start by importing Animated from React Native. Then we'll create the componentWillMount lifecycle method -- type this.animatedValue and assign it a new animated value.

[00:14] Next, we'll create a new variable called interpolateColor and assign it this.animatedValue.interpolate, which is a function that takes an object and an input range that defines the values that the animation will transition from -- that starts at 0and we'll say it goes to 150 -- and then an output range which will map to the values that are animating.

[00:42] We'll start with rgb(000which is black, and animate to rgb(51, 250, 170). We'll create a variable called const AnimatedStyle, and give it an object and a property of background color, and pass in our interpolateColor. Then we'll switch our box to an animated view and apply our new style.

[01:12] Let's create the componentDidMount lifecycle method. We use Animated.timing, which is a function that takes our animated value and the configuration object. We'll animate to 150 over the course of 1,500 milliseconds. Then we'll call start on our animation to trigger it.

[01:33] We're also going to make sure that we've set a default value of zero, otherwise our interpolate won't work. Now I'm going to refresh our emulator. We can see that it transitioned from a black to a green over the course of 1,500 milliseconds. Just because we interpolate, it does not mean that we can't use the animated value.

[01:51] Let's add transform, which is an array, which we can then pass various transforms. We'll add translateY and pass in this.animatedValue. Now, when we refresh our emulator, we can see that it both animates the color and the position at the same time.