oblador / react-native-animatable

Standard set of easy to use animations and declarative transitions for React Native
MIT License
9.84k stars 702 forks source link

[Bug?] Issues with using hooks #276

Open JakeHadley opened 5 years ago

JakeHadley commented 5 years ago

I'm working on animating an icon with hooks and react-native-animatable but I'm getting an error using the useRef hook. The error is undefined is not an object (evaluating 'iconRef.current.animatable.transitionTo').

I'm trying to figure out if this is an issue with the library or with how I'm using useRef or the library method. In the end, I want the icon to rotate when the button is pushed.

Reproducible snack here

import * as React from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';
import Icon from 'react-native-vector-icons/Entypo';
import * as Animatable from 'react-native-animatable';
const AnimatedIcon = Animatable.createAnimatableComponent(Icon);

const App = () => {
  const iconRef = React.useRef(null);
  const [rotated, setRotated] = React.useState(true);

  return (
    <View>
      <TouchableOpacity
        style={styles.container}
        onPress={() => {
          setRotated(!rotated);
          iconRef.current.animatable.transitionTo({
            transform: rotated ? [{ rotate: '0deg' }] : [{ rotate: '90deg' }],
          });
        }}>
        <Text style={{ fontSize: 30 }}>Press Me</Text>
      </TouchableOpacity>
      <AnimatedIcon
        name="chevron-small-right"
        ref={iconRef}
        size={50}
        style={{
          transform: [{ rotate: '0deg' }],
        }}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
    marginTop: 50,
  },
});

export default App;
danstepanov commented 5 years ago

Using const animationRef = useRef(), I'm able to reference the component via animationRef.current.fadeOutUp()

mohmdalfaha commented 4 years ago

I am facing the same issue, I have the exact thing @danstepanov mentioned with no hope.

mohmdalfaha commented 4 years ago

I resolved my issue which happened because I was giving a condition before the animatble.view to appear

eg:-

{
cart.total.length  > 0 && 
<Animatble.View ref={animationRef}>
 <Text> cart.total </Text>
</Animatble.View>
}

So your animation won't be applied in this case.

Instead, I changed the way the condition is applied like so:-

<Animatble.View 
style={{opacity: cart.total > 0 ? 1 : 0}}
ref={animationRef}>
 <Text> cart.total </Text>
</Animatble.View>

Then It worked nicely

Hope this helps someone :)

willryanuk commented 1 month ago

Yeah, if the Animatable.View isn't there on first load, then the useEffect callbacks just don't work (the current ref is not there). Quite a bit bug, and had me confused for quite a while.