When working with GSAP ScrollTrigger in React, you might encounter an issue where your pinned section disappears when scrolling from the top but works correctly when scrolling from the bottom. This issue usually happens due to improper cleanup or React's strict mode behavior.
Problem
- The section disappears when scrolling down.
- The pin works only when scrolling up.
- The .pin-spacer div is created incorrectly, affecting layout.
Solution
To fix this, we need to properly structure our GSAP animation using gsap.context() and ensure the cleanup process is handled correctly.
*Step-by-Step Fix
*
- Create a Separate Animation File
import gsap from "gsap";
import ScrollTrigger from "gsap/ScrollTrigger";
gsap.registerPlugin(ScrollTrigger);
export const useInspireAnimation = (sectionRef) => {
if (!sectionRef.current) return;
const ctx = gsap.context(() => {
gsap.to(sectionRef.current, {
scrollTrigger: {
trigger: sectionRef.current,
start: "top top",
end: "+=100%",
scrub: true,
pin: true,
markers: true, // Remove after debugging
},
});
gsap.fromTo(
sectionRef.current.querySelector("h1"),
{ opacity: 0, y: 50 },
{
opacity: 1,
y: 0,
duration: 1,
ease: "power2.out",
scrollTrigger: {
trigger: sectionRef.current,
start: "top 80%",
end: "top 50%",
scrub: true,
},
}
);
});
return () => ctx.revert(); // Cleanup GSAP context when c
- Implement in the Component
import { useEffect, useRef } from "react";
import { useInspireAnimation } from "./useInspireAnimation";
const InspiringSection = () => {
const sectionRef = useRef(null);
useEffect(() => {
const cleanup = useInspireAnimation(sectionRef);
return cleanup;
}, []);
return (
<section
ref={sectionRef}
className="section-2 h-screen w-screen bg-gray-900 text-white flex items-center justify-center"
>
<h1 className="text-4xl font-bold">Section 2</h1>
</section>
);
};
export default InspiringSection;
Why This Works?
- Ensures proper cleanup: Using ctx.revert() removes previous animations when the component unmounts.
- Uses gsap.context(): Prevents unexpected behavior in React Strict Mode.
- Prevents issues with pin-spacer: Ensures the pinning doesn't cause layout bugs.
- Keeps the animation separate: Improves maintainability and readability.
Final Thoughts
Using this method, you can prevent your pinned section from disappearing while maintaining smooth scroll-based animations in GSAP. If you're still facing issues, try adding ScrollTrigger.refresh() after a small delay to ensure GSAP recalculates the layout correctly.
Top comments (0)