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 also can't find anything related to this in the docs.

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; }} 

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobmppYmx%2BeIWOq5yam6Riu6LAyK%2BcZqqVlruqucCtnJ1lmaPBpr7PqKOarJVixKqw06FkqZ2imLKvwMCgnA%3D%3D

 Share!