Animate Colors with React Native Interpolate

Jason Brown
InstructorJason Brown
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 years ago

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.

Michel Arteta
Michel Arteta
~ 6 years ago

I am getting animated value is not a constructor when running the same code. Are you familiar with this error?

Luis
Luis
~ 4 years ago

Like many videos here on egghead, while useful this video lacks explanation. Instead use function X and pass parameters X and Y, one would expect some detail about the function's purpose, a bit more context overall.

Will Johnson
Will Johnson
~ 4 years ago

@Luis what do you need more context on? I'd be happy to to help!

Markdown supported.
Become a member to join the discussionEnroll Today