Reputation: 5782
I'm trying to do something extremely simple - have my button be transparent while not pressed, and change its background color to a different colour gradually when a user presses it. To achieve that, I'm using React Native Reanimated. Unfortunately, there's something wrong with my animation and I'm not sure what. The issue is this:
I change isPressed to true when the button is pressed and to false when the user moves his finger away from the button. Then I use that isPressed boolean to change the progress and finally use that progress to interpolate the colour from transparent to my other colour. Sadly what happens is this:
I press on the button and instead of the button changing its background color almost instantly, it takes like 5 seconds before turning to colors.primary50. Then if I unpress the button, it takes another 5 or so seconds to turn back to transparent. Also I don't really see gradual change in color, it just changes instantly.
const TertiaryButton: FunctionComponent<Props> = ({ title, wide = false, style, ...rest }) => {
const [isPressed, setIsPressed] = useState(false);
const progress = useSharedValue(0);
useEffect(() => {
progress.value = withTiming(isPressed ? 1 : 0, { easing: Easing.out(Easing.cubic), duration: 1000 });
}, [isPressed, progress]);
const rStyle = useAnimatedStyle(() => {
const backgroundColor = interpolateColor(progress.value, [0, 1], ['transparent', colors.primary50]);
return { backgroundColor };
});
return (
<Pressable onPressIn={() => setIsPressed(true)} onPressOut={() => setIsPressed(false)} {...rest}>
<Button
wide={wide}
style={[
style,
{
...rStyle,
},
]}
>
<ButtonText variant="h4">{title}</ButtonText>
</Button>
</Pressable>
);
};
Upvotes: 0
Views: 2051
Reputation: 71
The possible reason for this not working is that the Button
component may not be an Animated component. You need to make sure that Button
is an animated component. If it's a custom/library component, you can wrap it with Animated.createAnimatedComponent(...)
to make it an Animated component:
const AnimatedButton = Animated.createAnimatedComponent(Button);
Upvotes: 0
Reputation: 11
Try to change the progress value instantly inside onPressIn
and onPressOut
.
onPressOut={() => {
console.log("onPressOut")
isPressed.value = withTiming(0)
}}
onPressIn={() => {
console.log("onPressIn")
isPressed.value = withTiming(1)
}}
Upvotes: 1