I have a Pressable component and inside it I have an icon. I want to press it and rotate it 180 degrees, how can I do that?
CodePudding user response:
So to do this you must take use of the Animated library from react-native. In which you make animated values and make functions to update them. Here's a full sample of you want (https://snack.expo.dev/@heytony01/grumpy-pretzel) and below is the explantion.
First import the library and make an Animated value
import { Text, View, StyleSheet,Animated,TouchableWithoutFeedback } from 'react-native';
const spinValue = React.useState(new Animated.Value(0))[0]; // Makes animated value
Next define functions to change the value
// When button is pressed in, make spinValue go through and up to 1
const onPressIn = () => {
Animated.spring(spinValue, {
toValue: 1,
useNativeDriver: true,
}).start();
};
// When button is pressed out, make spinValue go through and down to 0
const onPressOut = () => {
Animated.spring(spinValue, {
toValue: 0,
useNativeDriver: true,
}).start();
};
The tricky part is that in order to rotate in react-native you need to pass "0deg" or "12deg" etc..
<View style={{
transform: [
{ rotate: "45deg" },
]
}}>
</View>
So what you do is you interpolate the animated value to "0deg" to "360deg"
// spinDeg will be between '0deg' and '360deg' based on what spinValue is
const spinDeg = spinValue.interpolate({
useNativeDriver: true,
inputRange: [0, 1],
outputRange: ['0deg', '360deg']
})
Lastly you pass in the spinDeg into your button and your done
// The animated style for scaling the button within the Animated.View
const animatedScaleStyle = {
transform: [{rotate: spinDeg}]
};
return (
<View style={{flex:1,justifyContent:"center",alignItems:"center"}}>
<TouchableWithoutFeedback
onPress={()=>{}}
onPressIn={onPressIn}
onPressOut={onPressOut}
>
<View style={{justifyContent:"center",alignItems:"center",backgroundColor:"lightgray",padding:15,borderRadius:20}}>
<Text>PRESS ME</Text>
<Animated.View style={[styles.iconContainer, animatedScaleStyle]}>
<Ionicons name="md-checkmark-circle" size={32} color="green" />
</Animated.View>
</View>
</TouchableWithoutFeedback>
</View>
);