Friday, 10 September 2021

How to stop at the nearest row using react-spring + decay?

I implement calendar which can be veristically dragged by a mouse. I would like to have some inertia on mouse release. I was able to achieve this functionality by using use-gesture + react-spring libs.

This is how it looks

enter image description here

The problem I would like to solve is how to force the inertia to stop at the nearest row? Currently it can be stopped at the middle of the row.

Here is my code. I removed some parts for simplicity

[...]
const [animatedOffsetY, animatedOffsetYProps] = useSpring(() => ({
  offsetY: 0,
  config: {
    decay: true
    frequency: 5.5,
  }
}))

[...]

const bind = useDrag((state) => {
  const [, currentY] = state.movement
  const [, lastOffsetY] = state.lastOffset
  const offsetY = lastOffsetY + currentY

  if (state.down) {
    setOffsetY(offsetY)
    animatedOffsetYProps.set({ offsetY: offsetY })
  } else {
    animatedOffsetYProps.start({
      offsetY: offsetY,
      config: {
        velocity: state.direction[1] * state.velocity[1],
      }
    })
  }
}, {
  from: [0, offsetY],
  bounds: { bottom: 0, top: (totalHeight - containerHeight) * -1 },
  rubberband: true
})

[...]

Update

I investigated, popmotion and framer-motion (which use popmotion under the hood) and they have modifyTarget prop which should solve my problem. I would prefer to stay with react-spring or custom solution.



from How to stop at the nearest row using react-spring + decay?

No comments:

Post a Comment