Building a pager component (Part 2)

We've setup the foundation of our component in the first part of this series, but it's nothing special as of yet. In this post, we will cover adding transitions between page changes to make it slightly more interesting.

In order to do so, let's use the excellent react-spring library, which will help us animate our transitions.

yarn add react-spring

...and import the functions we'll be using in our component:

import { useSpring, animated, interpolate } from 'react-spring'

The first thing we'll want to do is change our container view's translate value to a react-spring Animated.Value:

  // ... 

const offset = activeIndex * 100 * -1

// translateX will now represent a spring value that we will animate
// we'll set the initial value to our first offset here:
const [{ translateX }, set] = useSpring(() => ({
translateX: offset,
}))

// when the offset updates, we want to update the translateX value
// so that the spring will fire again:
useEffect(() => {
set({ translateX: offset })
}, [offset, set])

Animated.Value is a special object that will manage spring animations for us. Now, when the offset value changes, Animated.Value will update to a new value but with configurable easings. Theres a bunch of configuration that we can do here, but we'll stick with the defaults for now.

Since we've changed the offset to be an Animated.Value, we can't simply pass it into our transform function. Instead, we'll use the interpolate() function we imported above, and use that to convert Animated.Value's to ones we can pass into the style prop of our container div

  // update the container view to an animated.div 
// we'll use the interpolate() function to translate with our spring values
// this gives us a nice spring animation to our page transitions
return (
<animated.div
style=>
{React.Children.map(children, (element, index) => {
return (
<div
style=>
{element}
</div>
)
})}
</animated.div>
)

That's it! Each time the activeIndex value changes, we load a spring animation that will update the offset value, instead of immediately setting it like we had before. Here's what it now looks like:

Spring transitions between pages

Here's a fleshed out example of the above

CodeSandbox

Next up, we'll look at something a little more challenging -- handling swipe and pan gestures within our pager component.

Cheers!