ScriptS
Reactiflux4y ago
2 replies
Script

Script – 23-28 Apr 7

Working with framer motion

I need my animation to show when it reaches viewport with this logic below from stack overflow:
import { useInView } from "react-intersection-observer";
import { motion, useAnimation } from "framer-motion";

const Component = () => {
    const animation = useAnimation();    
    const [ref, inView, entry] = useInView({ threshold: 0.1 });

    useEffect(() => {
      if (inView) {
        animation.start("visible");
      } else {
        animation.start("hidden");
      }
    }, [animation, inView]);

    const variants = {
        visible: {
          y: 0,
          opacity: 1,
          transition: { duration: 0.5, delayChilden: 0.2, staggerChildren: 0.1 },
        },
        hidden: {
          y: enter,
          opacity: 0,
        },
    }
    return (
<>
        <motion.div
          ref={ref}
          animate={animation}
          initial="hidden"
          variants={{variants}}>TITLE 1</motion.div>
//---------CONTENTS HERE
        <motion.div
          ref={ref}
          animate={animation}
          initial="hidden"
          variants={{variants}}>TITLE 2</motion.div>
//---------CONTENTS HERE
       <motion.div
        ref={ref}
        animate={animation}
        initial="hidden"
        variants={{variants}}>TITLE 3</motion.div>
</>
      );
}

But using variants to reuse animation for different headings, the animation loads no longer until I reach the last heading of the page

I thought of having different variants for each title but that would just make my code messy. Is there any more cleaner way to sort this out?
Was this page helpful?