Reputation: 33
i'm new to react native and i'm trying to do a moving arrow after a variable get a value, I thought about using a switch case and changing the style, but it seemed impossible to change the padding properties, how could i solve this?
Upvotes: 0
Views: 1824
Reputation: 455
Your question needs a lot of information to be answered thoroughly so I will assume you use hooks, I will try to guide you by giving you an example.
The whole principle is to place your arrow in an 'absolute' position and animate it with an animation. Then, all you need to do is to set the value of the variable 'arrowValue', example : setArrowValue(0.3). Your arrow will then places itself at 30% (according to your interpolation) from the left of your container.
Here is a code snippet to show you the right way :
import {StyleSheet, View, Animated} from "react-native";
export default function ArrowMover(props)
{
// This is the value you will set and your arrow will automatically be placed
const [arrowValue, setArrowValue] = React.useState(0); // From 0 to 1 for example
// This is your animation
// It is the value you have to change to make your arrow move
const [animation, setAnimation] = React.useState(new Animated.Value(0));
// This is an interpolation of your animation
// See this as a black box, it allows you to output value (and ranges of values)
// based on the value of your animation
const animateArrowPosition = animation.interpolate({
inputRange: [0, 1],
outputRange: ["0%", "100%"],
});
// This is where everthing happens automatically
React.useEffect(() =>
{
moveArrowTo(arrowValue);
}, [arrowValue]); // Anytime 'arrowValue' changes, execute the 'moveArrowTo' function
const moveArrowTo = (newArrowValue) =>
{
Animated.timing(animation, { toValue: newArrowValue, duration: 500, }).start(() =>
{
// Do something (or nothing) once the animation finished
});
};
return(
<View style={s.container}>
// Your animation interpolation will change along with 'animation' to follow your interpolation
// of the value
<Animated.View style={[s.arrow, {left:animateArrowPosition}]}> // Notice the 'Animated.View'
<View>
// Your arrow (icon, image, etc...)
</View>
</Animated.View>
</View>
);
}
let s = StyleSheet.create(
{
container:
{
// Your container style
},
arrow:
{
// Your arrow style
height:30,
aspectRatio:1,
position:'absolute',
// left:0 (no need for that, your animation is taking care of the 'left' property
},
}
Upvotes: 1