Home > OS >  React native Animated stop is not working
React native Animated stop is not working

Time:02-17

I am trying to use React Native Animated to do simple animation with View width and Height. Following the official syntax from here React Animated. But the stop functionality is not working.

Here is my code snippet:

import React, { useRef } from "react";
import { Animated, View, StyleSheet, Button } from "react-native";

const App = () => {
 const sizeAnimBase = new Animated.Value(100);
 const sizeAnim = useRef(sizeAnimBase).current;
 
 const startAnimation = () => {
  Animated.timing(sizeAnim, {
      toValue: 500,
      duration: 100,
      useNativeDriver: false
    }).start(() => {
      
    });
 }

 const stopAnimation = () => {
  // Tried both ways but didn't work
  Animated.timing(sizeAnimBase).stop();
  Animated.timing(sizeAnim).stop();
 }

return (
 <View>
   <Animated.View
        style={
            width: sizeAnim, 
           height: sizeAnim
          }
      >
        <Text>Animated view</Text>
      </Animated.View>
    <Button title="Start Animation" onPress={startAnimation} />
        <Button title="Stop Animation" onPress={stopAnimation} />
 </View>
)
}

CodePudding user response:

This worked for me normally

const App = () => {
 const sizeAnim = useRef(new Animated.Value(100)).current;

  const startAnimation = () => {
    Animated.timing(sizeAnim, {
      toValue: 500,
      duration: 2000,
      useNativeDriver: false,
    }).start();
  };

  const stopAnimation = () => {
    Animated.timing(sizeAnim, {
      duration: 0,
      toValue: 0,
      useNativeDriver: true,
    }).stop();
  };

  return (
    <View>
      <Animated.View style={{width: sizeAnim, height: sizeAnim}}>
        <Text>Animated view</Text>
      </Animated.View>
      <Button title="Start Animation" onPress={startAnimation} />
      <Button title="Stop Animation" onPress={stopAnimation} />
    </View>
  );
}

CodePudding user response:

How are you testing whether it's working or not? You've set duration to 100ms, its practically impossible to press Stop Animation button before the animation completes.

Increase the duration to something like 5000ms and you'll set it's working perfectly.

Here is a snack link.

  • Related