Getting Started
This guide will help you set up GSAP in your React project and create your first animation.
Prerequisites
If this is your first time using GSAP, you should familiarize yourself with the basics. Learn about:
- GSAP Basics
- Tweens and timelines
- Animation controls
Understanding these concepts will help you control your animations better.
Installation
Step 1: Install GSAP
Add GSAP and the React integration package to your project:
pnpm add gsap @gsap/react
Run this command in your terminal in the root of your project (or frontend folder) where your package.json is located.
Step 2: Create Animation Configuration
Create an animations folder in your src directory, then create gsapConfig.ts:
import gsap from "gsap";
import { useGSAP } from "@gsap/react";
import SplitText from "gsap/SplitText";
// Register plugins here
gsap.registerPlugin(SplitText);
export { gsap, useGSAP, SplitText };
Note: If you're using the SplitText plugin (for text animations), make sure to import and register it as shown above. If you're only using basic animations, you can omit the SplitText import and registration.
Step 3: Create Animation Presets
Create basic-presets.ts (or presets.ts) inside the animations folder:
export const motion = {
// You will add all your presets here
}
Example Usage
Here's a complete example of how to use the animation presets in a React component.
Preset Definition
First, add a preset to your presets.ts file:
export const motion = {
fadeIn: (vars: gsap.TweenVars = {}): gsap.TweenVars => ({
autoAlpha: 0,
duration: 1,
ease: "power2.inOut",
...vars,
})
}
Component Usage
Then use it in your component:
import { useRef } from "react";
import { useGSAP, gsap } from "@/animations/gsapConfig";
import { motion } from "@/animations/basic-presets";
export default function Component() {
const ref = useRef<HTMLDivElement>(null);
useGSAP(() => {
const tl = gsap.timeline({ defaults: { ease: "power2.inOut" } });
tl.from("span", motion.fadeIn());
}, { scope: ref });
return (
<div ref={ref}>
<span>Example span</span>
</div>
)
}
This will create an animation on load that looks like this:
How It Works
-
useGSAP Hook: The
useGSAPhook from@gsap/reactmanages the animation lifecycle and automatically cleans up when the component unmounts. -
Timeline: GSAP timelines allow you to sequence multiple animations and control them as a group.
-
Scope: The
scopeoption inuseGSAPlimits the animation to elements within the ref, ensuring animations only target the intended elements. -
Presets: Animation presets are functions that return GSAP TweenVars objects, making it easy to reuse common animation configurations.
Next Steps
- Learn about Basic Animations - Fade, move, and scale effects
- Explore Text Animations - Split text animations with SplitText