This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Animate Colors with React Native Interpolate

2:11 React lesson by

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.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

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.

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.

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 0, and we'll say it goes to 150 -- and then an output range which will map to the values that are animating.

We'll start with rgb(0, 0, 0), which 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.

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.

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.

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.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?