I have 3 components. 2 of them run animations in parallel. Third must run animation consistently only after two components has complete their animation. How does to reach this with react-spring?
Asked
Active
Viewed 3,276 times
2
-
Move sall the components state to the parent component or Try using redux or mobx for central state management. Will make your life easier – uneet7 Sep 30 '19 at 10:18
1 Answers
3
There is an onRest callback in the common api. It is called when animation is finished. You can trigger a setState with them. And depending on that state you can trigger your third animation. Look out, that onRest will be called after every render even if you do not see change. So make sure that you limit the number of state changes if you do not want an infinite loop.
Something like this:
const AnimContainer = () => {
let [phase, set] = useState([0, 0]);
const props1 = useSpring({
from: { opacity: 0 },
to: { opacity: 1 },
config: { mass: 50, friction: 80 },
clamp: true,
onRest: () => !phase[0] && set([phase[0] + 1, phase[1]])
});
const props2 = useSpring({
from: { opacity: 0 },
to: { opacity: 1 },
onRest: () => !phase[1] && set([phase[0], phase[1] + 1])
});
const props3 = useSpring({
from: { opacity: 0 },
to: { opacity: phase[0] && phase[1] ? 1 : 0 },
clamp: true
});
return (
<>
<div>{"state: " + phase.join(", ")}</div>
<animated.div style={props1}>one</animated.div>
<animated.div style={props2}>two</animated.div>
{phase[0] > 0 && phase[1] > 0 && (
<animated.div style={props3}>three</animated.div>
)}
</>
);
};

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