blue
blue

Reputation: 7375

React Native - properly play Lottie on tap?

So my app is written in a functional component ( export default function App() { ) and I have other functional components within. One of them includes a Lottie animation:

function NavDot(props)
    {
      return (
      <TouchableWithoutFeedback onPress={() => onNavPress(props.id)}>
        <LottieView style={styles.lottieNav} source={require('./assets/circle.json')} />
      </TouchableWithoutFeedback>);
    }

This calls this function on press:

const onNavPress = (id) => {
    console.log(`nav ${id} pressed`);
  };

Which works, but may or may not be correct. Im having trouble passing the animation parameter from the LottieView into an external onPress function. I need to do animation.play() on press, per the Lottie docs, but referencing this in the functional component gives me "undefined" errors.

How can I play the Lottie animation (once, not loop) on tap like this?

Upvotes: 2

Views: 2606

Answers (1)

Erick Maeda
Erick Maeda

Reputation: 347

First, you don't have the variable this on function component.

If you are using Lottie from https://github.com/react-native-community/lottie-react-native you can check the following steps to try it working.

You need to import the React Hook useRef

import {useRef} from 'react';

On your component, you should create a variable to receive the reference to Lottie

function NavDot(props) {

  const LottieRef = useRef(null); // <---------------- Create reference variable

  return (
      <TouchableWithoutFeedback onPress={() => {
        onNavPress(props.id);
        LottieRef.current.play(); // <---------------- OnPress just call the lottieRef to animate it.
      }}>
        <LottieView 
            ref={LottieRef}
            style={styles.lottieNav} 
            source={require('./assets/circle.json')} 
        />
      </TouchableWithoutFeedback>
  );
}

Upvotes: 2

Related Questions