JoeBe
JoeBe

Reputation: 1290

How to use react native Animated API with "%" positioning values?

I have an SVG <line>, which I want to animate using the Animated API of react native. In particular I want to animate the x1 and x2 properties of the line using relative positioning with %. However, I cannot combine my animated value with a "%" string. The following code results in NaN% or [object Object]%:

import { Animated } from 'react-native';
import { Svg, Line } from 'react-native-svg';
const AnimatedLine = Animated.createAnimatedComponent(Line);

const myComponent = (props) => {
    //props.underlineX1 is something like: new Animated.Value(50)

    return(
        <Svg
            width="100%"
            height="100%">
            <AnimatedLine
                x1={`${props.underlineX1}%`} //or: x1={`${parseInt(props.underlineX1)}%`}
                x2={`${props.underlineX2}%`} //or: x2={`${parseInt(props.underlineX2)}%`}
                y1="40"
                y2="40"
                stroke={"green"}
                strokeWidth="2" />
        </Svg>
    )
}

What should I do to get values like 50% when props.underlineX1 = 50?

EDIT:

When using the JSON.stringify(props.underlineX1) + "%" method I receive the correct values for initial positioning, but the animation will not be executed (which works fine if I use the absolute values directly without the combination of "%").

Upvotes: 0

Views: 276

Answers (1)

Marek Lisik
Marek Lisik

Reputation: 2185

In order to transform an Animated.Value to your percentage string, you will need to interpolate like so:

const x1 = props.underlineX1.interpolate({
  inputRange: [0, 100],
  outputRange: ['0%', '100%'],
});

(note: this is assuming your animated values will be in the rage of 0-100)

Upvotes: 1

Related Questions