Some Examples » 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.

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.

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,
                    scale,
                    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, scale, rotate }}
            />
        )
    }
}

Join the Mighty Guides mailing list    ( ± 6 emails/year )

GDPR

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing per their Privacy Policy and Terms.



Leave a Reply