React-spring: Manually interpolation position

Created on 1 Nov 2019  路  1Comment  路  Source: pmndrs/react-spring

useSpring doesn't trigger animation if I call it with an empty object on the first iteration and then with from and to object. It's needed because for the first render I don't know the initial state for animation (I can read it only after component mounted).

For example, this doesn't work:
useSpring(position ? position : {});
May be It can be done with interpolating function?

There are codesandbox example
In that, I'm trying animate moving element to centre a container. Initially elements positioned with flexbox layout and then when item clicked it should be moved to centre container using absolute positioning. But this doesn't work, because useSpring ignore from property. How I can do that?

question

Most helpful comment

Copied from this comment:

You can set top and left to garbage values (like 0) until you have all the necessary data. If that results in a bad UX, you can hide the element until its actual top and left are computed. In the future, you'll be able to set initial values _after_ the first render, and useSpring will forcefully re-render to ensure the new animated values are "hooked up" to their animated component(s).

So, provide garbage values when position is falsy:

const spring = useSpring(position ? position : {from: {left: 0, top: 0}});

For the setPosition call, you need reset: true to ensure the from prop is respected.

>All comments

Copied from this comment:

You can set top and left to garbage values (like 0) until you have all the necessary data. If that results in a bad UX, you can hide the element until its actual top and left are computed. In the future, you'll be able to set initial values _after_ the first render, and useSpring will forcefully re-render to ensure the new animated values are "hooked up" to their animated component(s).

So, provide garbage values when position is falsy:

const spring = useSpring(position ? position : {from: {left: 0, top: 0}});

For the setPosition call, you need reset: true to ensure the from prop is respected.

Was this page helpful?
0 / 5 - 0 ratings