Search code examples
reactjsreact-spring

Animation using react-spring interpolate function not working


I am trying to understand how the react-spring interpolation works.

Here is my spring:

const { x } = useSpring({ from: { x: 0 }, x: 100, config: { duration: 1000 } }) 

Here is how I am using it:

...
return (
  <animated.div style={{
    background: "lightblue",
    height: "100%",
    width: x.interpolate([0, 0.5, 1], [0, 100, 0]).interpolate(x => `${x}%`)
  }} />
)

The interpolation happens but it is not rendered.
Here is a sandbox: https://codesandbox.io/s/amazing-panini-fzn54?fontsize=14&hidenavigation=1&theme=dark

Can you help me figure out what's wrong with this code?


Solution

  • It is almost there. If you want to use range, in the interpolation from [0, 0.5, 1] to [0, 100, 0] Then you should change the x value between 0 and 1.

    So I would change this part:

    const { x } = useSpring({ from: { x: 0 }, x: 1, config: { duration: 1000 } }) 
    

    I also fixed the codesandbox, but it is a little different it uses the renderprops api.

    https://codesandbox.io/s/tender-varahamihira-6nic7?file=/src/App.js:63-123