Drag example: Step-by-step

Matt PerryMatt Perry

In this tutorial, we'll build the Drag example step-by-step.

This example is rated 1/5 difficulty, which means we'll spend some time explaining the Motion APIs that we've chosen to use (and why), and also any browser JavaScript APIs we encounter that might be unfamiliar to beginners.

Introduction

The Drag example shows how to make an element draggable with Motion for React. It uses the drag prop, which allows users to move elements around the page with mouse or touch input.

Compared to implementing draggable elements with raw browser APIs, Motion's drag prop provides several advantages:

Get started

Let's start by creating a simple box that we'll make draggable:

"use client"
 
export default function Drag() {
    return <div style={box} />
}
 
/**
 * ==============   Styles   ================
 */
 
const box = {
    width: 100,
    height: 100,
    backgroundColor: "#2f7cf8",
    borderRadius: 10,
}

This creates a blue square on the page, but it doesn't do anything yet.

Let's animate!

Import from Motion

To make our box draggable, we first need to import the motion component from Motion for React:

import { motion } from "motion/react"

Basic functionality

Now we can replace the standard div with a motion.div and add the drag prop:

export default function Drag() {
    return <motion.div drag style={box} />
}

That's it! With that single drag prop, our box is now fully draggable. Users can click or touch the element and move it around the page.

By default, the draggable element will:

Customizing the drag behavior

While the basic drag functionality is powerful, you can customize it in many ways:

Constraining to an axis

If you want to restrict movement to just horizontal or vertical:

// Only horizontal dragging
<motion.div drag="x" style={box} />
 
// Only vertical dragging
<motion.div drag="y" style={box} />

Adding constraints

You can limit how far the element can be dragged:

<motion.div
    drag
    dragConstraints={{
        top: -50,
        left: -50,
        right: 50,
        bottom: 50,
    }}
    style={box}
/>

This keeps the element within 50 pixels of its starting position in all directions.

Controlling momentum

By default, elements have a natural momentum when released. You can disable this:

<motion.div drag dragMomentum={false} style={box} />

Visual feedback during drag

You can also add visual effects while the element is being dragged:

<motion.div drag whileDrag={{ scale: 1.1 }} style={box} />

This makes the element grow slightly while being dragged.

Conclusion

In this tutorial, we learned how to:

Motion for React makes creating draggable UIs much simpler than traditional methods, requiring minimal code while providing a polished, natural-feeling user experience.

Tutorial Project

We're currently working on adding a tutorial for every example on the Motion Examples website. So far, 12% of examples have a tutorial.