React-Native-Reanimated Interpolate Width Percentage
I Am Converting Some of My Default Animated Stuff to React-Native-Reanimated V2 and Can't Seem to Figure out How to Interpolate a Value to a String Percentage...
I am converting some of my default Animated stuff to react-native-reanimated v2 and can't seem to figure out how to interpolate a value to a string percentage. I also can't find anything related to this in the docs.
Using Animated from react-native I could just do:
width: widthAnim.interpolate({
inputRange: [0, 1],
outputRange: ['0%', '100%'],
})
But the interpolate() function from reanimated only takes number params, so how can I animate the width then?
interpolate(widthAnim.value, [0, 1], ['0%', '100%'])
// err: Type 'string' is not assignable to type 'number'.
2 Answers
You can simply use template literal
width: `${widthAnim.value * 100}%`
Check out more official example
A full example to complete the previous response:
const searchViewAnimatedWidth = useSharedValue(0);
const searchBoxAnimatedStyle = useAnimatedStyle(() => {
const interpolatedWidth = interpolate(
searchViewAnimatedWidth.value,
[0, 1],
[40, 100],
{ extrapolateRight: Extrapolation.CLAMP }
);
return {
width: withTiming(`${interpolatedWidth}%`, {
duration: 500,
useNativeDriver: false,
}),
};
});
<Animated.View
style={{...otherStyles,...searchBoxAnimatedStyle}}>
...
</Animated.View>
And in your trigger
onPress={() => {
searchViewAnimatedWidth.value = searchViewAnimatedWidth.value == 0 ? 1 : 0;
}}