Skip to content
Advertisement

Dragging not working for react-use-gesture

For some reason, I just cannot get the most basic example of react-use-gesture to work. What I am trying to do is just have a square follow my mouse location when you drag it. I copy-pasted the example from their documentation multiple times (https://github.com/pmndrs/react-use-gesture) and still cannot get it to work. I just don’t understand it anymore. I created a stackblitz to show you my code. What am I still doing wrong?

Stackblitz with code: https://stackblitz.com/edit/react-mg2u8p?file=src/Square.js

I will also include the most relevant code here:

import React from "react";
import { useSpring, animated } from "react-spring";
import { useDrag } from "react-use-gesture";

const Square = () => {
  const [{ x, y }, set] = useSpring(() => ({ x: 0, y: 0 }));
  const bind = useDrag(({ down, movement: [mx, my] }) => {
    set({ x: down ? mx : 0, y: down ? my : 0 });
  });

  return (
    <animated.div
      {...bind()}
      className="Square"
      style={{ x, y, touchAction: "none" }}
    />
  );
};

export default Square;

Advertisement

Answer

It’s a version problem.

Your example uses code for react-spring version 9+, but the version of react-spring you’re using in the example is 8.0.27.

The example the documentation gives for version 8 is this:

import { useSpring, animated } from 'react-spring'
import { useDrag } from 'react-use-gesture'

function PullRelease() {
  const [{ xy }, set] = useSpring(() => ({ xy: [0, 0] }))
  // Set the drag hook and define component movement based on gesture data
  const bind = useDrag(({ down, movement }) => {
    set({ xy: down ? movement : [0, 0] })
  })
  // Bind it to a component
  return (
    <animated.div
      {...bind()}
      style={{
        transform: xy.interpolate((x, y) => `translate3d(${x}px, ${y}px, 0)`),
      }}
    />
  )
}

So in your case you would only need to change PullRelease to Square and add className="Square" to the animated.div like you had it in your question.


For both the documentation on the v8 and v9 implementation of this using React UseGesture see this.

If you want to use the v9 version, you currently need to install react-spring@next according to the documentation (see previous link).

Advertisement