I have an Animated.View in React Native which I am animating the width of.
const pollRef = useRef(new Animated.Value(0)).current;
const resultWidth = ((votes/totalVotes)*100).toFixed(0) // GET A PERCENTAGE VALUE
const AnimateResult = () => {
Animated.timing(pollRef, {
toValue: resultWidth,
duration: 3000,
useNativeDriver: false
}).start();
};
useEffect(() => {
AnimateResult()
},[])
<Animated.View
style={{
position: 'absolute',
top: 0,
left: 0,
height: '100%',
width: pollRef,
backgroundColor: '#155A8B',
}}
/>
The value of resultWidth (and therefore pollRef) is 100. The width of the element is animating fine, apart from it's correctly treating the 100 as an absolute value and animating the width to 100 pixels, whereas I would like to express it as a percentage. Whatever syntax I use in the style object I can't seem to do it.
I have tried things like:
style={{
...
width: "'"+pollRef+"%'"
...
}}
and
style={{
...
width: `${pollRef}%`,
...
}}
But neither worked. I have also noticed that there seems to be whitespace around the variable - if I console log:
console.log('pollRef:',pollRef,'X')
the output is:
pollRef: 0 X
which may make adding a percentage sign to the end a little more difficult.
Any help very much appreciated.
I think https://stackoverflow.com/a/48741068/12637199 answers your question.
You need to use interpolate to transform numbers to strings.
You can just have:
const animation = new Animated.Value(0);
const inputRange = [0, 100];
const outputRange = ["0%", "100%"]
const animatedWidth = animation.interpolate({inputRange, outputRange});
And then use it like this:
width: animatedWidth,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With