Search code examples
javascriptreactjsframer-motion

useSpring breaks scroll tied animation Framer Motion


I've set up a scroll animation on an element that's tied to the scroll progress of it's parent container with Framer Motion:

const Test = ({ children }: Props) => {

    const scrollRef = useRef(null);

    const { scrollYProgress } = useScroll({
        target: scrollRef,
    });

    const x = useTransform(scrollYProgress, [0, 0.2], ["100%", "0%"]);

    return (
        <Container ref={scrollRef}>
            <Sticky style={{ x }}>{children}</Sticky>
        </Container>
    );
};

The above works as expected until I bring useSpring() into the mix:

    const x = useSpring(useTransform(scrollYProgress, [0, 0.2], ["100%", "0%"]), {
        stiffness: 100,
        damping: 30,
        restDelta: 0.001,
    });

After some error testing I discovered that the percentage values:["100%", "0%"] when combined with useScroll() seem to be the culprit. The animation behaves as expected if I swap them out with just numbers ([100, 0]).

I've tried separating out useScroll() and useTransform() like so:

    const xPos = useTransform(scrollYProgress, [0, 0.2], ["100%", "0%"])

    const x = useSpring(xPos, {
        stiffness: 100,
        damping: 30,
        restDelta: 0.001,
    });

but this doesn't work either.

Any idea how I can get this working with percentage values?


Solution

  • I have this same problem and finally have a solution to this

     const { scrollYProgress } = useScroll({
        target: scrollRef,
    });
    
     const temporaryx = useSpring(scrollYProgress, {
        stiffness: 100,
        damping: 30,
        restDelta: 0.001,
      });
    
    let x = useTransform(temporaryx, [0, 0.2], ["100%", "0%"])
    

    So basically you use the useSpring function on the scrollYprogress motion value, this way the spring animation should be applied, I hope this help