Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Animate the Width of a View by a Percentage Value in React Native?

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.

like image 938
Ray Purchase Avatar asked Sep 16 '25 15:09

Ray Purchase


1 Answers

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,
like image 55
lmasneri Avatar answered Sep 19 '25 04:09

lmasneri