Tips for justifyContent using framer-motion's scrolling interpolation
P粉238433862
P粉238433862 2023-08-31 18:42:45
0
1
378
<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粉238433862
P粉238433862

reply all(1)
P粉293341969

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>
  )

}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!