Search

13. Drag: Transform

13. Drag: Transform

This example uses the useMotionValue() and useTransform() hooks to transform the drag distance (x) to scale and rotate values.

⚡️ Some Examples – 13 – Drag: Transform
open in CodeSandbox

Pretty simple. The box is made draggable (only horizontally), with drag constraints that let it bounce back. And its snap-to-constraints animation is tweaked a bit.

There’s an x Motion value passed to the box through style so that we’ll get its horizontal position, which we transform with useTransform() to scale and rotate values.

export function Example() {
    const x = useMotionValue(0);
    const scale = useTransform(x, [-150, 150], [1.5, 0.5]);
    const rotate = useTransform(x, [-150, 150], [-90, 90]);

    return (
        <motion.div
            style={{
                width: 150,
                height: 150,
                borderRadius: 30,
                backgroundColor: "#fff",
                x,
                scale,
                rotate,
            }}
            drag="x"
            dragConstraints={{ left: 0, right: 0 }}
            dragTransition={{ bounceStiffness: 600, bounceDamping: 20 }}
        />
    );
}

Leave a Reply

Scroll to Top