Code:
Key points in this implementation
- When the
layout
prop is present on a motion component, drag
will no longer update the element's x
/y
transforms. Instead, it updates its "viewport box". - We can use
onViewportBoxUpdate
event to retrieve the information of this viewport box update:
<motion.div drag onViewportBoxUpdate={(box, delta) => {...}}>
- We can trigger a re-render to "reset" an element's layout position. Try commenting out
onDragEnd
in the code to see the effect of this. - When calcuating the
targetIndex
, we apply a small offset to prevent infinite loop:
const targetIndex = Math.round(delta.y.translate / height
- 0.2 * Math.sign(delta.y.translate)
) + index