in

Change the lottie animation based on the react state


I am trying to create an open/close menu button. I apply a state, called ‘openMenu’, to hold the current state of the menu display (closed or opened). Also I want to animate it. The idea is display one of two different animations depending on this state so I add two Lottie animations to a div and use conditional rendering to return just one as you can see in the code,

function SettingButton() {

// save the animation instance
const animationToOpen = useRef();
const animationToClose = useRef();

// a boolean state to manage the settings
const [openMenu, setOpenMenu] = useState(true);
const [animation, setAnimation] = useState(animationToOpen);

function click() {
    // change the state
    changeState();
    startAnimation();
}

function startAnimation() {
    // reset the animation
    animation?.current?.setSeeker(1, true)

    // play the animation
    animation?.current?.play();
}

function changeState() {
    // change the menu state
    setOpenMenu(!openMenu);

    // select the chunk of frames of the animation depending on the state
    setAnimation(openMenu ? animationToOpen : animationToClose);
}



return (
    <div onClick={click} className="setting-button-container">
        {   // check which anymation should play
            openMenu === true && (
                <LottieControl
                    linkRef={animationToOpen}
                    src={animationToOpenSrc}
                    size={[300, 300]}>
                </LottieControl>
            )
        }
        {
            openMenu === false && (
                <LottieControl
                    linkRef={animationToClose}
                    src={animationToCloseSrc}
                    size={[300, 300]}>
                </LottieControl>
            )
        }
    </div>
);

The problem is that react, after change the state, start the animation and then re-render the elements, canceling the animation progress.

I also tried use useRef() to call the startAnimation function after render but it doesn’t work neither.
I would apreciate any help and thanks in advance 🙂



Source: https://stackoverflow.com/questions/70600284/change-the-lottie-animation-based-on-the-react-state

A basic and minimal e-commerce store using Gatsby, Stripe, Use-Shopping-Cart and Netlify

Skia Canvas : ERR_DLOPEN_FAILED