Reputation: 113
I am currently working on a next.js application and my goal is to have a "greeting animation" with sound.
I am having problems triggering an event when the animation starts, so I can start the music synchronized.
This is my code, which displays the animation but does not log anything:
import React, { useEffect, useRef } from "react";
import lottie from "lottie-web";
function App() {
const container = useRef(null);
useEffect(() => {
lottie.loadAnimation({
container: container.current,
renderer: "svg",
loop: false,
autoplay: true,
animationData: require("../media/lottie/greeter.json")
});
return () => {
lottie.play();
};
}, []);
return (
<div className="dark-bg h-screen pointer-events-none"
ref={container}
onAnimationStart={() =>console.log("test")}
/>
);
}
export default App;
Appreciate any help!
Upvotes: 2
Views: 2886
Reputation: 113
I found out what the problem was. I added the event the wrong way and had to use the "DOMLoaded" event.
This works for me:
import React, { useEffect, useRef } from "react";
import lottie from "lottie-web";
function App() {
const container = useRef(null);
useEffect(() => {
const anim = lottie.loadAnimation({
container: container.current,
renderer: "svg",
loop: false,
autoplay: true,
animationData: require("../media/lottie/greeter.json")
});
anim.addEventListener('complete', function(e) { console.log('element ended'); });
anim.addEventListener('DOMLoaded', function(e) { console.log('element loaded'); });
return () => {
lottie.play();
};
}, []);
return (
<div className="dark-bg h-screen pointer-events-none"
ref={container}
/>
);
}
export default App;
Upvotes: 2
Reputation: 161
Seeing as you autoplay the animation, you can listen for the "DOMLoaded" event or if you wanted the "enterFrame" event and then ignore subsequent calls to your callback, as it will be called on every frame played of your animation.
Upvotes: 0