Horizontal Scroll Tutorial
I'm Lenny Muffler, and this is the exact pattern I use to build cinematic horizontal scroll moments with GSAP and ScrollTrigger in React. First we need to import GSAP and ScrollTrigger and register it.
1import gsap from "gsap"
2import { ScrollTrigger } from "gsap/ScrollTrigger"
3gsap.registerPlugin(ScrollTrigger)Next we need to create the panels we want to scroll through horizontally. We need to give the main section an id like "horizontal-scroll" and the panels classnames like "panel" so we can target them with GSAP, make them fullscreen with the classes "w-full h-full" and cover them in another div with the class flex flex so they dont appear stacked vertically but instead horizontally.
1<section id="horizontal-scroll">
2 <div className="h-screen flex">
3 <article className="panel w-full h-full">Panel 1</article>
4 <article className="panel w-full h-full">Panel 2</article>
5 <article className="panel w-full h-full">Panel 3</article>
6 </div>
7</section>Now all thats left is to set up the GSAP ScrollTrigger. First we need to make use of the useGSAP hook that works very similar to the useEffect. Then we just need to put all of our sections in an array, we can select them with our main element with the id "horizontal-scroll" and its children with the class "panel", set up our scrollTrigger to begin at the element with the id "horizontal-scroll". We also need to activate the options scrub and pin to make the scroll smooth and pin the element while scrolling.
1useGSAP(() => {
2 const panels = gsap.utils.toArray<HTMLElement>("#horizontal-scroll .panel")
3 if (!panels.length) return
4
5 gsap.to(panels, {
6 xPercent: -100 * (panels.length - 1),
7 ease: "none",
8 scrollTrigger: {
9 trigger: "#horizontal-scroll",
10 pin: true,
11 scrub: 0.5,
12 end: window.innerWidth * (panels.length - 1),
13 },
14 })
15 })