Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6214

How to animate expanding / collapsing a text preview in react native with Animated.View

$
0
0

I'm creating a text component that I want to be 2 lines by default, and if the user taps on it, it will expand to the full length, and if the user taps on it again, it will collapse back to 2 lines.

So far I have something like this in my return function:

<TouchableWithoutFeedback    onPress={() => {      toggleExpansion();    }}><Animated.View style={[{ height: animationHeight }]}><Text      style={styles.textStyle}      onLayout={event => setHeight(event.nativeEvent.layout.height)}      numberOfLines={numberOfLines}>      {longText}</Text></Animated.View></TouchableWithoutFeedback>

My state variables and toggleExpansion function look like this:

const [expanded, setExpanded] = useState(false);const [height, setHeight] = useState(0);const [numberOfLines, setNumberOfLines] = useState();const toggleExpansion = () => {  setExpanded(!expanded);  if (expanded) {    setNumberOfLines(undefined);  } else {    setNumberOfLines(2);  }};

So far this works to expand and collapse but I'm not sure how to set the Animated.timing function to animate it. I tried something like this:

const animationHeight = useRef(new Animated.Value(0)).current;useEffect(() => {  Animated.timing(animationHeight, {    duration: 1000,    toValue: height,    easing: Easing.linear  }).start();}, [height]);

but it didn't quite work. It doesn't display the text at all, and when I try initializing the new Animated.Value to a bigger number than the 2 line height (like 50), the height always gets truncated to 16 no matter how many times I expand and collapse. What's the best way to animate expanding and collapsing the text?


Viewing all articles
Browse latest Browse all 6214

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>