0

I have a View in my React Native screen that I want to display and then fade out after 5 seconds. Here's the view inside the render() method:

{this.state.showView (
  <Animated.View style={{ opacity: this.state.fadeAnim }}>
  </Animated.View>
)}

There's a button on the screen, when I tap on the button, I want to toggle between displaying and hiding the view. Nothing is animated here, but 5 seconds after the view is displayed, I want to fade it out. Here's what I have in the onPress() event of the button.

  onPress = () => {
    if (this.state.showView) {
      this.setState({
        ...this.state,
        fadeAnim: new Animated.Value(0),
        showView: false,
      });
    } else {
      this.setState(
        {
          ...this.state,
          fadeAnim: new Animated.Value(1),
          showView: true,
        },
        () => {
          Animated.timing(this.state.fadeAnim, {
            toValue: 0,
            duration: 2000,
            delay: 5000,
          }).start(() => {
            this.setState({
              ...this.state,
              fadeAnim: new Animated.Value(0),
              showView: false,
            });
          });
        },
      );
    }
  };

This doesn't work. The view is displayed and disappeared as expected, but it doesn't fade out; it just disappears without animation. What am I doing wrong?

ataravati
  • 8,891
  • 9
  • 57
  • 89
  • im guessing you have it set up so that the showView state displays and hides the component? if then it looks like you start the animation at the same time you make the component hide or show, therefore cutting out the animation altogether. You need to make a five second setTimeout or try an async promise to wait for the animation to finish before setting the state to hide or show. – Matt Berg Feb 20 '20 at 22:31
  • @MattBerg, you're right, but isn't `delay: 5000` supposed to do exactly what you are saying? – ataravati Feb 20 '20 at 22:35
  • it looks like in your first if statement you set the fading out animation to play and at the same time set the component to showView: false ? im not sure what the Animated.Value(0) and Animated.Value(1) animations are, but this is just my guess... – Matt Berg Feb 20 '20 at 22:39
  • I tried that, but it didn't work. – ataravati Feb 20 '20 at 22:46

0 Answers0