Roy
Roy

Reputation: 1922

How to revert the Draggable compoent's position when drag stops using React

I have a Draggable component with a container in it. I want the position of the Draggable to reset when the dragging is stopped (onStop). This is my Draggable's properties:

<Draggable
    axis="x"
    bounds={{top: 0, bottom: 0, left: -75, right: 0}}
    onStop={//what to do here}
>

How can I do that?

Upvotes: 0

Views: 1726

Answers (2)

Ancellery
Ancellery

Reputation: 1

Create a position state

    const [pos, setPos] = useState({x:0, y:0});

Set the position state when the Draggable component moves using onDrag

    const [pos, setPos] = useState({x:0, y:0});
    const handleDrag = (e, data)=>{
        setPos({x:data.x, y:data.y});
    }
    <Draggable onDrag={(e, data) => handleDrag(e, data)}/>

Set the position back to 0 when the drag ends using onStop

    const [pos, setPos] = useState({x:0, y:0});
    const handleDrag=(e, data)=>{
        setPos({x:data.x, y:data.y});
    }
    const handleDragStop=()=>{
        setPos({x:0, y:0});
    }
    <Draggable onDrag={(e, data) => handleDrag(e, data)} 
    onStop={handleDragStop}/>

Set the postion of the draggable component as the state using position

    const [pos, setPos] = useState({x:0, y:0});
    const handleDrag=(e, data)=>{
        setPos({x:data.x, y:data.y});
    }
    const handleDragStop=()=>{
        setPos({x:0, y:0});
    }
    <Draggable onDrag={(e, data) => handleDrag(e, data)} 
    onStop={handleDragStop} 
    position={pos}/>

Upvotes: 0

Roy
Roy

Reputation: 1922

So, I researched and you can just use position={{x: 0, y: 0}} to make it work.

Upvotes: 2

Related Questions