Animation » Example Animations » 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.

Code component

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

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

Code override

export function Drag_Transform(Component): ComponentType {
    return (props) => {
        const { style, ...rest } = props

        const x = useMotionValue(0)
        const scale = useTransform(x, [-150, 150], [1.5, 0.5])
        const rotate = useTransform(x, [-150, 150], [-90, 90])

        return (
            <Component
                {...rest}
                drag="x"
                dragConstraints={{ left: 0, right: 0 }}
                dragTransition={{ bounceStiffness: 600, bounceDamping: 20 }}
                style={{ ...style, x: x, scale: scale, rotate: rotate }}
            />
        )
    }
}

Leave a Reply