Search code examples
react-spring

what does interpolation really do


beginner here, i'm having trouble understanding interpolation with usespring in React spring library , im trying to make an element go back and forth with the translate css property, now what i do understand is that passing in a range emulates css key frames and the output is the values the element should have at that point of the animation so i did something like,

const {xyz} = useSpring({
  from: {xyz: [0, 0, 0]},
  to: {xyz: [0, 200, 0]},
})

<animated.div className={classes.down} style={{
  transform: xyz
    .interpolate(([y]) => (
    {range: [0, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 1],
    output: [180, 220, 180, 220, 180, 220, 180, 200]}
    ))
    .interpolate((x, y, z)=> translate(${x}px, ${y}px, ${z}px))
  }}>
    <Typography variant="body2" className={classes.downText}> 
       Scroll Down
    </Typography>
    <DownArrow className={classes.downIcon}/>
</animated.div>

which dosen't work


Solution

  • There is a lot of problem here.

    First of all in the useSpring if you want to change only the y then you can eliminate the x and z.

    Secondly the range not worked for me with arrow function parameter.

    Finally you must use translate3d instead of translate and the backtick is missing for the template string.

    Something like this:

      const { y } = useSpring({
        from: { y: 0 },
        to: { y: 1 }
      });
    
      return (
        <div className="App">
          <animated.div
            style={{
              transform: y
                .interpolate({
                  range: [0, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 1],
                  output: [180, 220, 180, 220, 180, 220, 180, 200]
                })
                .interpolate(y => `translate3d(0px, ${y}px, 0px)`)
            }}
          >
            Scroll Down
          </animated.div>
        </div>
      );
    

    https://codesandbox.io/s/gracious-diffie-rgz06?file=/src/App.js:135-613