computerjazz / react-native-infinite-pager

An infinitely-swipeable pager component.
MIT License
175 stars 16 forks source link

Can't detect swipe direction #6

Closed ryanliljestrom closed 2 years ago

ryanliljestrom commented 2 years ago

I want to use this package to make something similar to react-native-calendar-strip for a project. One of our requirements is that a date is always selected as the user swipes through the weeks.

The functionality I want:

I can't currently find a way to detect if the swipe is a left swipe or a right swipe. I think if onPageChange were modified to provide the previous page as an (optional) second argument, it would give me the information I need

computerjazz commented 2 years ago

hm, not a bad idea to include prev data in onPageChange.

You can get the info you want via an animated reaction using the index and pageAnim props, see this snack: https://snack.expo.dev/@computerjazz/infinite-pager-detect-direction

here's the important part:

  const [message, setMessage] = useState("")

  useAnimatedReaction(() => {
    return Math.round(pageAnim.value)
  }, (val, prev) => {
    if (val !== prev && prev !== null) {
        const isActive = val === index
        if (isActive) {
          const swipeDirection = val - prev > 0 ? 'forward' : 'back'
          console.log(`Page ${index}, is active, user is swiping ${swipeDirection}`)
          runOnJS(setMessage)(`user swiped ${swipeDirection}`)
        }
    }
  }, [pageAnim])