I want to make a react component initiates the animation whenever I click it. There are some options:
- if i change the props at middle of the animation, it should re-animate form the start.
- changing of the props is triggered by a button of another node.
here’s my code i tried:
function Button() {
const indexRef = useRef(0);
const clickHandler = () => {
indexRef.current++;
}
return (<button onClick={clickHandler}><SkillWindow data={somedata[indexRef]}/></button>)
}
interface SkillWindow extends DefaultProps {
data: SkillData;
}
function SKillCard({ data, className }: SkillWindow) {
const id: string = "skillcard--0";
useEffect((): void => {
const target: HTMLElement | null = document.getElementById(id);
if (!target) return;
target.addEventListener("click", (): void => {
target.style.animationPlayState = "paused";
});
target.style.animation = "running";
}, [data]);
const { name, desc }: SkillData = data;
const style: TailwindProperties = {
xl: "xl:w-96 xl:ml-8 xl:pb-8 xl:flex xl:flex-col xl:items-center xl:gap-8",
base: "bg-neutral-200 bg-opacity-75 _swash-in",
};
return (
<section className={`${style.xl} ${style.base} ${className}`} id={id}>
<WindowPanel />
<div className="w-40 h-40 rounded-full bg-black" />
<div className="flex flex-col gap-4 items-center">
<h1 className="text-lg font-bold">{name}</h1>
<h2 className="text-base font-normal">hello</h2>
<p className="text-base font-normal">{desc}</p>
</div>
</section>
);
}
export default SKillCard;
2
Answers
you have to modify the
useEffect
hook to make your react component SkillCard. whenever you click on or change its props, restart its animation. to each skillcard assign a unique id based on the data. by this the component recognizes it as a new instance. When the data changes use the dependency array to trigger re-animation, also change the animation logic touseEffect
. Here is the example:You’ve to trigger animation in the useEffect only if the element is animating already. Make an animationStatus state and modify it when you start the animation (here, in the event handler) & add the respective checks in useEffect. Hope this helps