iosreact-nativereact-hooksexpolottie

React Native Icon Not Playing When App Starts


import React from "react";
import LottieView from "lottie-react-native";
import { useEffect, useRef } from "react";

function CarAnim(props) {
  const animationRef = useRef(null);
  useEffect(() => {
    if (animationRef.current) {
      animationRef.current.play();
    }
  }, []);
  return (
    <LottieView
      ref={animationRef}
      autoPlay
      loop
      style={{
        width: 200,
        height: 200,
      }}
      source={require("../assets/carAnimJs.json")}
    />
  );
}

export default CarAnim;

I am running the emulator on my iPhone using Expo but when my animation is first initially mounted on my screen, the animation does not play, but later on when I am make a change in the React project or in its file, the animation begins playing perfectly fine.

I tried using ref hooks but I am still getting the same results. The animation is there, but it doesn't play or start a loop until a change is made in the file and it is re-rendered.


Solution

  • I think the component where you're trying to show the animation, but the component isn't mounted yet, so add the timeout function to delay the running of the code to show the animation, where 2000 is the amount of seconds you want to wait

    useEffect(() => {
      setTimeout(() => {
       if (animationRef.current) {
        animationRef.current.play();
       }
      },2000);
    }, []);