Course contentsShow
← React
Lesson 2004 of 2,39645. AnimationsFree lesson

Refs and Multiple Elements: gsap.utils.selector

Animating multiple children efficiently using selector utilities and array refs in React components.

Refs and Multiple Elements: gsap.utils.selector

What you'll learn: How to animate multiple child elements efficiently in React using GSAP's selector utility instead of managing individual refs for every element.

The Problem with Animating Many Elements

When you need to animate multiple children (like list items or card grids), creating a separate ref for each element becomes unwieldy. Imagine having 20 list items—that's 20 separate useRef() calls and manual assignments. There's a better way.

GSAP's Selector Utility

gsap.utils.selector() creates a scoped querySelector function tied to a parent ref. Think of it like giving GSAP a "search zone"—it only looks for elements within that parent container, making your code cleaner and more React-friendly.

How It Works

function AnimatedList() {
  const containerRef = useRef(null);

  useEffect(() => {
    // Create a scoped selector for the container
    const q = gsap.utils.selector(containerRef);

    // Animate all .list-item elements inside containerRef
    gsap.from(q('.list-item'), {
      opacity: 0,
      y: 50,
      duration: 0.5,
      stagger: 0.1 // Each item animates 0.1s after the previous
    });
  }, []);

  return (
    <div ref={containerRef}>
      <div className="list-item">Item 1</div>
      <div className="list-item">Item 2</div>
      <div className="list-item">Item 3</div>
    </div>
  );
}

The q() function works like querySelector, but scoped to your ref's DOM node. GSAP can target multiple elements at once, and properties like stagger create sequential animations automatically.

Key Takeaway: Use gsap.utils.selector(parentRef) to create a scoped query function for animating multiple child elements without managing individual refs—cleaner code, more powerful bulk animations.