Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using React Native Animated to fade in and out elements

I am new to react native animated feature. I am hoping to use it to fade in and out elements on button press. The below code works to fade in the element when the page loads, but the button to fade it out does not fade it out as I would expect. Can someone explain what I am doing wrong. Thank you.

class FadeComponent extends Component {

  constructor(props) {
    super(props)
    this.state = {
      fadeAnim: new Animated.Value(0),  // Initial value for opacity: 0
    }
    this.fadeOut = this.fadeOut.bind(this);
  }

  componentDidMount() {
    Animated.timing(          // Animate over time
      this.state.fadeAnim,    // The animated value to drive
      {
        toValue: 1,           // Animate to opacity: 1 (opaque)
        duration: 2000,       // 2000ms
      }
    ).start();                // Starts the animation
  }

  fadeOut(){
    this.setState({fadeAnim: new Animated.Value(1)})
    Animated.timing(          // Animate over time
      this.state.fadeAnim, // The animated value to drive
      {
        toValue: 0,           // Animate to opacity: 1 (opaque)
        duration: 2000,       // 2000ms
      }
    ).start();                // Starts the animation
  }

  render() {
    let { fadeAnim } = this.state;

    return (
      <View style = {{ backgroundColor: '#1a8cff', marginTop: 100 }}>

        <Animated.View style={{ ...this.props.style, opacity: fadeAnim }} >
          {this.props.children}
          <View style = {{ backgroundColor: '#000000', height: 50, width: 50 }}>
          </View>
        </Animated.View>

        <TouchableOpacity onPress={this.fadeOut} >
          <Text style={{ color: 'white', textDecorationLine: 'underline', marginTop: 10 }}>
          fade out
          </Text>
        </TouchableOpacity>

      </View>
    );
  }
}
like image 314
panderson9149 Avatar asked Jul 27 '18 02:07

panderson9149


People also ask

How do you use the transition effect in React Native?

The transition animation is one of the easiest ways to easily animate a React Native application. It provides a way to create a seamless change between various states in your application. In this tutorial, we will be exploring the Transition API and a use-case where the transition animation can be employed; Dark mode.


1 Answers

Because function setState is asynchronous. This should fix your issue:

this.setState({ fadeAnim: new Animated.Value(1) },
  () => {
    Animated.timing(          // Animate over time
      this.state.fadeAnim, // The animated value to drive
      {
        toValue: 0,           // Animate to opacity: 1 (opaque)
        duration: 2000,       // 2000ms
      }
    ).start();
  })
like image 148
KienLV Avatar answered Sep 29 '22 13:09

KienLV