Categories
JavaScript Answers React Native Answers

How to run code when an animation is complete with React Native?

Spread the love

Sometimes, we want to run code when an animation is complete with React Native.

In this article, we’ll look at how to run code when an animation is complete with React Native.

How to run code when an animation is complete with React Native?

To run code when an animation is complete with React Native, we can put the code that we want to run when the animation is done in the callback we pass into start.

For instance, we write:

import * as React from 'react';
import { View, Text, Animated } from 'react-native';
import { Card } from 'react-native-paper';

const App = () => {
  const fadeAnim = React.useRef(new Animated.Value(100)).current;
  const [finished, setFinished] = React.useState(false);

  const fadeOut = () => {
    Animated.timing(fadeAnim, {
      toValue: 0,
      duration: 3000,
    }).start(() => setFinished(true));
  };

  React.useEffect(() => {
    fadeOut();
  }, []);

  return (
    <View>
      <Animated.View
        style={[
          {
            opacity: fadeAnim,
          },
        ]}>
        <Text>Fading View</Text>
      </Animated.View>
      {finished && <Text>Finished</Text>}
    </View>
  );
};
export default App;

to add an animated view.

We set the opacity style to fadeAnim to animate the opacity to fade out the ‘Fading View’ text.

To start the animation, we call Animated.timing with the fadeAnim animation variable.

The duration of the animation is 3000 milliseconds.

And we animate the opacity to 0 as specified by the toValue.

We call start with a function that calls setFinished to set finished to true.

And then we call fadeOut in the useEffect hook callback which is called with an empty array to run the animation when the page loads.

As a result, we see the Fading Out text fade and the Finished text shown after the animation is done.

Conclusion

To run code when an animation is complete with React Native, we can put the code that we want to run when the animation is done in the callback we pass into start.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *