Home  >  Q&A  >  body text

Tips for justifyContent using framer-motion's scrolling interpolation

<p>I have a piece of code that animates between x values, but it doesn't work when trying to transition from justify-content: center to left. </p> <p>The following is a code snippet: </p> <pre class="brush:php;toolbar:false;">function Navbar() { const { scrollY } = useScroll(); const x = useTransform(scrollY, [0, 100], ["center", "left"]); return ( <motion.div layout className={styles.parent} style={{ justifyContent: x, display: "flex" }} transition={{ duration: 0.5 }} > <Image src="/BlackLogo-2.svg" alt="Cg Logo" width={100} height={100} style={{padding: 20,}} priority /> </motion.div> ) }</pre></p>
P粉238433862P粉238433862387 days ago379

reply all(1)I'll reply

  • P粉293341969

    P粉2933419692023-09-01 09:20:19

    I found a solution. You just use the useMotionValueEvent function to check if the scroll is past a certain point and set it as state, then you have to wrap your child element (my image) in motion.div and also set the class in the outer div like below Show:

    function Navbar() {
      const { scrollY } = useScroll();
      const [Scrolled, setScrolled] = useState(false);
      
      useMotionValueEvent(scrollY, "change", (latest) => {
        if (latest > 200) {
          setScrolled(true);
        }
        else {
          setScrolled(false);
        }
      })
    
      return (
        <div 
          style={{justifyContent: Scrolled? "left" : "center"}}
          className={styles.icon}
        > 
          <motion.div
          layout
          transition={{type: "spring", stiffness: 700, damping: 30}}
          >
            <Image
              src="/BlackLogo-2.svg"
              alt="Cg Logo"
              width={100}
              height={100}
              style={{padding: 20,}}
              priority
            />
          </motion.div>
        </div>
      )
    
    }

    reply
    0
  • Cancelreply