Subscribing to and Manipulating Animations

  • We can manually provide the MotionValue to a motion element to listen to a value.
import { motion, useMotionValue } from "framer-motion"

export function MyComponent() {
  const x = useMotionValue(0)
  return <motion.div style={{ x }} />
}
  • The useTransform hook lets you map a range of motion values to another range.
"use client";
 
import { motion, useMotionValue, useTransform } from "framer-motion";
 
export function Example() {
  const y = useMotionValue(0);
  const opacity = useTransform(y, [0, 100], [1, 0]);
  
  return (
    <div className="h-1/2">
      <motion.div
      // pan instead of drag, because we want to move the element based on the motion value
        onPan={(_, info) => {
          y.set(info.offset.y);
        }}
        onPanEnd={() => y.set(0)}
        style={{ y, opacity }}
        className="h-10 w-10 cursor-grab rounded-full bg-gray-400"
      />
    </div>
  );
}