I have a component and everytime the prop data is changed
I want to animate the component in order to adjust it to the new height.
The Animated.View gets an Value as a height style prop, but when I change the Value after componentDidUpdate the Value is not updated, unless I call forceUpdate and then it works.
function runTiming(clock: Animated.Clock, startValue: Animated.Value<number>, destValue: Animated.Value<number>, duration: number) {
const state = getInitialState(startValue);
const config = getConfig(destValue,duration);
return block([
cond(clockRunning(clock), 0, [
set(state.finished, 0),
set(state.time, 0),
set(state.position, startValue),
set(state.frameTime, 0),
set(config.toValue, destValue),
startClock(clock),
]),
timing(clock, state, config),
cond(state.finished, stopClock(clock)),
state.position,
]);
}
export class Component extends PureComponent<PropsType> {
heightAnimation: any;
constructor(props: PropsType) {
super(props);
this.heightAnimation = new Animated.Value(0);
this.animate();
}
componentDidUpdate(prevProps: PropsType) {
if (propsChangedAndNeedToUpdateHeight) {
this.animate()
}
}
animate = () => {
this.heightAnimation = runTiming(new Clock(), new Animated.Value(oldHeight), new Animated.Value(destHeightValue), 400);
this.forceUpdate(); //I want to delete this line
}
render() {
return (
<Animated.View style={{
height: this.heightAnimation
}
}>
{MyComponent}
</Animated.View>
);
}
}
I have the same issue. How can I update a Value in the animation after its been initialized with a prop?
@yoavtsook2806 could you share forceUpdate? Is it just re-rendering the entire View?
This issue is very similar to https://github.com/software-mansion/react-native-reanimated/issues/295
@yoavtsook2806 could you share forceUpdate? Is it just re-rendering the entire View?
see the code above, in the animate function I use:
this.forceUpdate();
this is a function of react that let you to rerender the component as you imagined.
the issue is really similar to what you described, but there is no real answer there as well.
We know we can initialize an animation based on props. All we're looking to do is update an animation based on props. The same thing we're able to do everywhere else in React.
Hey @noobvim. Each animated value has setValue method. It might allow you to set a new value based on the props. Have you tried it already?
To update Animated.Value you need to use .setValue as @terrysahaidak suggested. forceUpdate detaches and reattaches nodes in the native side, that's why it's working.
Most helpful comment
We know we can initialize an animation based on props. All we're looking to do is update an animation based on props. The same thing we're able to do everywhere else in React.