Fade in an Image with React Native

In this lesson you will learn how to gradually fade in images in React Native in order to eliminate the jarring flash associated with an image rendering. We will take a look at the Image component onLoad property and use it, in conjunction with the Animated API, to accomplish the desired user experience.

You must be a Member to view code

Instructor: 00:00 the first thing we'll do is import the animated library from React Native. We'll then go ahead and create a new component called Image Loader, which extends component. We'll then initialize it with some state. That state's going to be opacity, and we'll set that to a new animated.value and set that initially to zero.

00:21 We'll then set up a new function called unload, and inside of this unload, we're going to call "Animated.timing." We'll say we want to modify this.state.opacity. Then, we need to pass a configuration to the second argument of animated.timing. We'll set a to-value of one. We'll set a duration of 500 milliseconds.

00:41 Finally, we want to say we want to use the native driver, so this animation happens off of the JavaScript thread. Finally, we need to call a .start on our animated.timing. We'll then set up our render method. Inside of our render method, we'll return a new animated.image. Inside of this animated.image, we'll add our unload, in which we'll call this ".unload."

01:07 We'll then use the spread operator to pass any of the props that are typically passed to an image component to our animated image. Finally, we'll start setting up our styles. We'll use an array to pass our styles so that we can go ahead and pass all of the existing styles, as well.

01:22 First, we'll have an object in which we'll set the opacity, which we'll pull from this.state.opacity. We'll then set up a transform through which we'll actually modify the scale of the image, which again, we'll use this.state.opacity. This time, we'll call .interpolate on it, and we'll say the input range is zero to one, which we're setting in our state.

01:43 We'll then set the output range, which will be from 085 when the input's at 0to a final value of 1. Finally, we want to make sure we that pass in all of the user supply's styles to the image as well.

01:55 We can then go ahead and take our image loader component and replace the image component that we're already using. When we save this, you can see that the image now fades in and scales in as it's loading...