I am trying to get a scroll trigger background animation to work on Next.js, like the air pods example many have posted. I am having a lot of trouble, and there is no great documentation for next.js specifically. I understand from reading many forum posts the gsap logic should be inside useEffect().
I am runnning into a few errors with this not rendering at all or trigger.revert is not function errors and etc. I appreciate any help. Thank you for your time.
Here is a simplified version on my code:
// Landing Page
import Head from "next/head";
import LightExplosion from "../public/gif/LightExplosion.webp";
import Image from "next/image";
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/dist/ScrollTrigger";
import { useRef, useEffect } from "react";
function Landing() {
const boxRef = useRef(null);
if (typeof window !== "undefined") {
gsap.registerPlugin(ScrollTrigger);
}
useEffect(() => {
let frame_count = 9;
let offset_value = 100;
const t = gsap.to(boxRef, {
scrollTrigger: {
trigger: boxRef,
start: "top top",
end: "+=" + frame_count * offset_value,
pin: true,
scrub: true,
},
});
// Clean up before unmounting the component/page
return () => {
t.kill();
ScrollTrigger.getAll().forEach((e) => e.kill());
};
}, []);
return (
<html>
<div>
<Head>
<title>Home</title>
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, viewport-fit=cover"
></meta>
<meta name="description" content="Description Here."></meta>
</Head>
<div>
<div className="-z-30 absolute top-0 right-0 bottom-0 left-0">
<Image
src={LightExplosion}
ref={boxRef}
layout="fill"
objectFit="cover"
/>
</div>
<component_here />
<component_here_two />
</div>
</div>
</html>
);
}
export default Landing;