Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useRef hooks doesn't work with lottie-react-native

I have upgraded my class component to functional component hooks, but right now the ref does not work.

Before:

class A extends Component{

   animation = null;

   onPress = ()=> {
      this.animation.play();
   }

   render(){
     return (
        <View>
          <LottieView
            source={require('./file.json')}
            ref={animation => {this.animation = animation}}
          />
          <Button onPress={this.onPress} title='click me' />
        </View>
     );
   }
}

The above code which it is class Component works very well.

But the following code which I upgraded doesn't work.

Updated code:

const A = props => {

   const animation = useRef(null);

   const onPress = ()=> {
      animation.play();
   }

   return (
        <View>
          <LottieView
            source={require('./file.json')}
            ref={animation}
          />
          <Button onPress={onPress} title='click me' />
        </View>
   );
}
like image 208
Muhammad Avatar asked Oct 08 '19 09:10

Muhammad


1 Answers

You're missing .current.

See working example at: https://snack.expo.io/@zvona/lottie-and-useref-example

const onPress = () => {
  animation.current.play();
}
like image 170
Samuli Hakoniemi Avatar answered Sep 24 '22 19:09

Samuli Hakoniemi