0

Using react-spring and react-use-gesture I want to have a carousel animation that can be activated by dragging OR clicking on a button.

I've figured out a solution: https://codesandbox.io/s/viewpager-6o78r?file=/src/index.js

Putting a setTimeout in a loop for frames of the animation, but I feel like there must be a better way. The way I'm doing it probably isn't as smooth because I don't have easing etc. Is there a way to use the from and to properties on the springs I've already created for use by the drag gestures?

Bill Johnston
  • 1,160
  • 1
  • 14
  • 31

1 Answers1

0

I'm not used much the useSprings function yet, but I think I came up with a simpler solution:

  const handleNextPage = () => {
    if (index.current < pages.length - 1) {
      index.current = index.current + 1
      set(i => ({
        x: (i - index.current) * window.innerWidth,
        scale: 1,
        display: 'block'
      }))
    } 
  }

I also added an optional animation when you are at the end of the images, to have a feedback, that you are at the end. It has two state a 100 pixel oversoot and back. I made the two state with timeout, but it might be done a more elegant way.

  const handleNextPage = () => {
    if (index.current < pages.length - 1) {
      index.current = index.current + 1
      set(i => ({
        x: (i - index.current) * window.innerWidth,
        scale: 1,
        display: 'block'
      }))
    } else {
      set(i => ({
        x: (i - index.current) * window.innerWidth - 100
      }))
      setTimeout(
        () =>
          set(i => ({
            x: (i - index.current) * window.innerWidth
          })),
        500
      )
    }
  }

The whole example: https://codesandbox.io/s/viewpager-5pgl5?file=/src/index.js

Peter Ambruzs
  • 7,763
  • 3
  • 30
  • 36