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>
);
}
}
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.
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();
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With