Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Animate Colors with React Native Interpolate

    Jason BrownJason Brown
    react-nativeReact Native
    0.35 - 0.39

    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.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    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 0and 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(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.

    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.