How do you transition framer motion values?

3.3k Views Asked by At

I have a motion value that is updated whenever a component is being hovered. I thought that framer-motion automatically took care of animating the value to its new state but apparently it doesn't. How can I transition the new values of my motion value? It is also important to note that I'm aware of the whileHover prop that exists but I don't want to use it here. This example component illustrates my situation:

const Component = () => {
    const scale = useMotionValue(defaultScale);

    return (
        <motion.img
        style={{ scale }}
        onMouseEnter={ () => scale.set(1.35) }
        onMouseLeave={ () => scale.set(defaultScale) }
        />
    )
} 
1

There are 1 best solutions below

1
On BEST ANSWER

Have you tried useSpring?

const Component = () => {
  const scale = useSpring(1);

  return (
    <motion.div
      style={{ scale, background: "tomato", width: "100px", height: "100px" }}
      onMouseEnter={() => scale.set(1.35)}
      onMouseLeave={() => scale.set(1)}
    />
  );
};

Docs: https://www.framer.com/api/motion/motionvalue/#usespring

Or you can also use useAnimation to create custom controls and transitions:

const Component2 = () => {
  const controls = useAnimation();

  return (
    <motion.div
      style={{ background: "blue", width: "100px", height: "100px" }}
      animate={controls}
      onMouseEnter={() => controls.start({ scale: 1.35 })}
      onMouseLeave={() => controls.start({ scale: 1 })}
    />
  );
};

Docs: https://www.framer.com/api/motion/animation/#animation-controls

Codesandbox with both examples: https://codesandbox.io/s/httpsstackoverflowcomquestions64077992-j63qv?file=/src/App.js