I want to create a smooth animation where a View box slides down to its actual height. If the maximum height of the View, which is the height required to display all the contents, is less than 70, there is no need for an animation. However, if the maximum height exceeds 70, then I set the description height to 70. When the view is clicked, it should animate towards the maximum height. This is my objective.
Unfortunately, I am facing difficulties with the onLayout function in obtaining the necessary content height. Below is my code:
function card() {
const [expandedDescription, setexpandedDescription] = useState(false);
const [descriptionHeight, setdescriptionHeight] = useState(new Animated.Value(0))
const [layoutCount, setlayoutCount] = useState(0)
const [maxContentHeight, setmaxContentHeight] = useState(0);
const getContentHeight = (event:any) => {
setmaxContentHeight(event.nativeEvent.layout.height);
if(maxContentHeight < 70){
setdescriptionHeight(new Animated.Value(maxContentHeight));
}
else{
setdescriptionHeight(new Animated.Value(70));
}
}
const toggle = () => {
console.log(maxContentHeight);
if(maxContentHeight > 70){
Animated.timing(descriptionHeight, {
toValue: expandedDescription ? descriptionHeight : maxContentHeight,
duration: 300,
}).start();
setexpandedDescription(!expandedDescription);
}
}
return (
<View style={styles.cardContainer}>
<Animated.View style={[styles.descriptionContainer, {height:descriptionHeight}]} onLayout={(event:any) => getContentHeight(event)} >
<Text style={styles.descriptionHeaderText}>Description</Text>
<TouchableOpacity onPress={() => toggle()}>
<Text style={styles.descriptionText}>Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Aenean bibendum tincidfffffffffunt libero, nec luctus dolor consequat
quis. Phasellus portalike elephants and had to work hard to earn their while chicken
</Text>
</TouchableOpacity>
</Animated.View>
</View>
)
}
const styles = StyleSheet.create({
cardContainer: {
width: '95%',
marginBottom: 10,
backgroundColor: '#ffffff',
borderRadius:25,
height: 'auto',
alignItems:'center',
paddingLeft: 10,
paddingRight: 10,
},
descriptionContainer:{
width: '100%',
alignItems:'center',
marginTop: 10,
padding:5
},
descriptionHeaderText:{
fontSize: 15,
color:'#8E8E8E',
},
descriptionText:{
marginTop: 5,
},
});
export default card;
When I try to run the onLayout function to get the text box height dynamically, the animation starts behaving strangely. It either jumps between 0 and the maximum height or just stays at 0. Any suggestions or assistance would be greatly appreciated!