Preserved position for draggable Framer Motion components
P粉449281068
P粉449281068 2024-03-31 22:29:49
0
1
418

I'm creating a widget dashboard where you can move widgets around, my goal is to preserve the position of the widgets after dragging them so that they can be loaded in the exact same location in future sessions.

Here's a codesandbox that illustrates the issues I'm having with framer-motion: https://codesandbox.io/p/sandbox/interesting-sun-p8h6cu.

The initial

top and left values ​​on the widget correctly reflect its starting position, but I cannot retain its new position after dragging it.

I'm updating the position of the widget in the onDragEnd handler, which in turn updates the top and left styles on the widget. Dragging via Framer-motion using transform:translate and updating the positioning style results in a widget:

  1. Correctly retain its new position on DragEnd
  2. Move in the UI after the previous point because the top left style doubles the effect of the transform:translate dragging style.

I don't know how to solve this problem. I tried using transform:translate for initial positioning but it doesn't work. Also, now I think the framer motion overrides it once it's dragged, causing different unwanted behavior.

TLDR: I'm having trouble displaying absolutely positioned components that can be dragged via Framer-motion's drag functionality

P粉449281068
P粉449281068

reply all(1)
P粉621033928

You are right, top and left will be doubled because the Framer drag function is changing x and y . Since you then apply the xy transformation to the top and left, you get unexpected results.

If you only change x and y, everything should stay in sync.

style={{ x: widget.x, y: widget.y }}

instead of

style={{ left: widget.x, top: widget.y }}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template