Question: Is there any better way to rewrite my code without using setTimeout
?
use useGSAP
in React.
If I use console.log(parentRef)
in child.tsx
, it will get null
.
parent.tsx
export default function Page() {
const parentRef = useRef(null);
return (
<main className="flex min-h-screen flex-col p-6">
<div
className="flex h-20 shrink-0 items-end rounded-lg bg-dark-slate-gray p-4 md:h-52"
ref={parentRef}
>
<Logo parentRef={parentRef} />
</div>
</main>
);
}
child.tsx
export default function Logo({ parentRef }: LogoProps) {
const container = useRef<HTMLDivElement>(null);
const setupAnimation = () => {
const parentWidth = parentRef.current?.getBoundingClientRect().width;
gsap.to(container.current, { x: parentWidth, rotation: 10 });
};
useGSAP(
() => {
setupAnimation();
},
{ scope: container }
);
return (
<div
className={`${lusitana.className} flex flex-row items-center leading-none text-wheat`}
ref={container}
>
<GlobeAltIcon className="h-12 w-12 rotate-[15deg]" />
</div>
);
}
I tried adding setTimeout
to my code, and it worked correctly. It ensures that parentRef
elements are fully rendered before being accessed.
child.tsx
useGSAP(
() => {
setTimeout(() => {
setupAnimation();
}, 100);
},
{ scope: container }
);