Viewport Trigger
Animate elements as they enter and exit the viewport
Scroll down to see boxes animate in
ViewportTrigger.tsx
'use client';
import { useRef } from 'react';
import { useGSAP } from '@gsap/react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
export function ViewportTrigger() {
const containerRef = useRef<HTMLDivElement>(null);
useGSAP(() => {
const boxes = gsap.utils.toArray<HTMLElement>('.box');
boxes.forEach((box) => {
gsap.from(box, {
opacity: 0,
y: 50,
duration: 0.8,
scrollTrigger: {
trigger: box,
start: 'top 80%',
end: 'top 50%',
toggleActions: 'play none none reverse',
},
});
});
}, { scope: containerRef });
return (
<div ref={containerRef} className="space-y-8">
{[1, 2, 3].map((i) => (
<div key={i} className="box p-8 bg-surface rounded-lg">
Box {i}
</div>
))}
</div>
);
}