I have lottie animations as json
, and I’m using react-lottie to animate them in my page.
I have 4 items which goes like:
const items = [
{
animationData: layer1Animation,
title: 'social gaming experiences',
description: 'we develop entertaining engagement formats on the best social gaming platforms. We are platform agnostic, being able to build experiences on Roblox, Fortnite, Minecraft as well as custom proprietary solutions using Unreal Engine and Unity',
},
// and others
];
and I have state called activeIndex
to update the index after every 3 seconds:
const [activeIndex, setActiveIndex] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setActiveIndex((prevIndex) => (prevIndex + 1) % items.length);
}, 4000);
return () => clearInterval(interval);
}, [items.length]);
and the defaultOptions
object for Lottie:
const defaultOptions = {
loop: false,
autoplay: true,
animationData: items[activeIndex].animationData,
rendererSettings: {
preserveAspectRatio: 'xMidYMid slice',
},
};
and lastly I’m rendering the jsx
as:
<div className={styles.container}>
<h3>but what are our actual solutions?</h3>
<div className={styles.cart_items}>
{items.map((item, index) => (
<div
key={index}
className={`${styles.cart_item} ${index === activeIndex ? styles.active : styles.inactive}`}
>
<div className={styles.image_container}>
<Lottie options={defaultOptions} />
</div>
<div className={styles.content}>
<p>{item.title}</p>
<span>{item.description}</span>
</div>
</div>
))}
</div>
<div className={styles.animation_slider}>
{items.map((_, index) => (
<div
key={index}
onClick={() => setActiveIndex(index)}
className={index === activeIndex ? styles.active : styles.inactive}
></div>
))}
</div>
</div>
The problem is that it does not work as I expect, the animation is a bit off, so it does not start (or change to next animation) when index changes.
How it should be:
You can also check the code at this codesandbox.