What is the best method of adding onPress animations to React Native Typescript projects?

173 Views Asked by At

I've tried using "react-native-animatables" to create animations and it works, but I cannot figure out how to implement it to work onPress. Here's what i've tried so far.

...
    const flip = {
    from: {
      rotateY: false ? '0deg' : '180deg',
      rotate: !false ? '0deg' : '0deg',
      translateX: 0,
      translateY: 0,
    },
    to: {
      rotateY: false ? '0deg' : '0deg',
      rotate: !false ? '0deg' : '0deg',
      translateX: -140,
      translateY: 51,
    },
  }

  const AnimationRef = useRef(null);
  const _onPress = () => {
    if(AnimationRef) {
      AnimationRef.current?.flip();
    }
  }
...

return (
  ...

  <TouchableWithoutFeedback onPress={_onPress}>
    <Animatable.Image 
      animation={ tada } 
      duration={ 1500 }
      delay={ 1000 }
      iterationDelay={ 2500 }
      easing="linear"
      iterationCount="infinite"
      source={ tempegg } 
      style={{
        
        resizeMode: "contain",
        width: 250,
        height: 250,
        marginTop: -25,
        right:"15%",
        borderRadius:1000,
      }}
    />
  </TouchableWithoutFeedback>
  ...

The code compiles and everything, but there is an error at AnimationRef.current?.flip(); where it says "Property 'flip' does not exist on type 'never'." And when I click on the image, nothing happens. How would I get the onPress to work properly?

1

There are 1 best solutions below

0
On

if (animationRef) will always return true; the ref is created when you invoke the hook. animationRef.current is what you want to check for. This is I think your main issue - I don't see that you're assigning the ref anywhere. Try adding ref={animationRef} to your Image:

  <Animatable.Image 
    ref={animationRef}
    ...

Then the ref will get defined on the first render.

I'm not familiar with the animatable API, so I don't know if the rest of the way you've set up the animation will work. I know the ref won't be defined without adding that line to the component though.