GSAP Basic
Install the GSAP package.
npm install gsap
npm install @gsap/react
Init the GSAP object in the layout or page component, and register plugins. More templates and examples can be found here.
app/layout.tsx
'use client';
import gsap from "gsap";
import { useGSAP } from "@gsap/react";
if (typeof window !== 'undefined') {
gsap.registerPlugin(useGSAP);
}
export default function Layout({ children }: { children: React.ReactNode }) {
return <main>{children}</main>;
}
The useGSAP hook allows you to use GSAP in your components with performance in mind.
components/my-component.tsx
import { useGSAP } from "@gsap/react";
import { useRef } from "react";
export function MyComponent() {
const container = useRef<HTMLDivElement>(null);
useGSAP(
() => {
gsap.to('h1', { x: 100 });
},
{ scope: container }
);
return (
<div ref={container}>
<h1>My Component</h1>
</div>
);
}
The gsap.to(), gsap.from(), and gsap.fromTo() methods are used to create basic tween animations.
components/tween.tsx
"use client";
import { useGSAP } from "@gsap/react";
import gsap from "gsap";
import { useRef } from "react";
export default function Tween() {
const containerRef = useRef<HTMLDivElement>(null);
useGSAP(
() => {
// gsap.to()
gsap.to("#blue-box", {
x: 100,
duration: 1,
repeat: -1,
});
// gsap.from()
gsap.from("#red-box", {
x: 100,
duration: 1,
repeat: -1,
});
// gsap.fromTo()
gsap.fromTo(
"#green-box",
{
x: 100,
duration: 1,
},
{
x: 200,
duration: 1,
repeat: -1,
}
);
},
{
scope: containerRef,
}
);
return (
<div ref={containerRef} className="space-y-1">
<div id="blue-box" className="size-10 rounded bg-blue-500"></div>
<div id="red-box" className="size-10 rounded bg-red-500"></div>
<div id="green-box" className="size-10 rounded bg-green-500"></div>
</div>
);
}GSAP provides a variety of easing that you can use to create smooth animations. To use it, you can pass the easing to the animation options. Check all the available easing here.
gsap.to("#blue-box", {
x: 100,
duration: 1,
repeat: -1,
ease: "power4.out",
});
The following animations use the same properties except for the easing. Notice how different easing functions affect the motion.
power4.out
power4.inOut
elastic.inOut
GSAP makes it easy to sequence multiple animations using gsap.timeline(). You can add multiple animations to a timeline and they'll play one after another in order.
gsap
.timeline()
.to("#blue-box", {
x: 200,
duration: 1,
})
.to("#green-box", {
x: 200,
duration: 0.5,
delay: 0.5,
});
To be able to control the placement of the animations in the timeline, you can use the position parameter.
If you have the same tween animations for multiple elements, you can use the stagger parameter to control the delay between the animations.
gsap.to(".box", {
x: 200,
duration: 1,
stagger: 0.5,
});