Search code examples
reactjsreact-nativereact-native-ios

Animated.Text fade-in animation on change


so i am receiving text from a web socket connection, and adding it to a Text component. It starts off as grey, and then turns into black after x amount of time ( The app processes the text ). I have the code below

    <Text style={styles.confirmedText}>
       {this.state.confirmedText}

       <Animated.Text style={{ fontFamily: "Helvetica Neue", color: "#9b9b9b" }}>
              {this.state.tempText}
       </Animated.Text>
    </Text>

So this tempText is constantly changing, but i want there to be a fade-in animation when the text goes from an empty string -> some / any text at all. Any ideas how i could do this?

Note: i know my code hasn't attempted to implement this but I haven't been able to find any working samples using Animated.Text to follow.

Thanks in advance,

EDIT: Better yet, if temp had a value of say "some text", and a word was added to it, eg "some text plus", the added word "plus" to be animated in individually would be great. Seems difficult though


Solution

  • First, you'll want to set up an Animated value like this:

    this.opacity = new Animated.Value(0)
    

    Then, when you receive the text you'll want to start the animation:

    Animated.timing(this.opacity, {
        duration: 350, // some number in milliseconds
        toValue: 1, // or whatever final opacity you'd like
      }).start();
    

    Finally, you'll need to interpolate that value on your Animated.Text component:

    style={{
      opacity: this.opacity.interpolate({
        inputRange: [0, 1],
        outputRange: [0, 1],
        extrapolate: 'clamp',
      }),
      ...
    }}
    

    Hopefully, that can get you started!