Adjust the scrollview height dynamically at runtime

Viewed 544

I am developing a react-native project.

I have a ScrollView in MyComponent, the content of ScrollView consists of :

  • a MySubComponent,
  • a Text
  • a Image component

All the content/data of above components have dynamic length or height. So, I would like adjust the content height of my ScrollView on the fly at runtime.

To achieve that my plan is to disable automaticallyAdjustContentInsets of the ScrollView as you can see from my below code snippet. Then, have a state variable to hold the latest value of contentInsetBottom. But I am not sure how can I calculate the height of child components so that I can call setContentInsetBottom(totalHeight) to update the content height of my ScrollView .

(I am pretty sure my plan will work if I know how to calculate the height of each child component of my ScrollView.)

Anyone can guide me a bit?

const MyComponent = ({myText, image}) => {

   // I have a state of the contentInsetBottom for the ScrollView
   const [contentInsetBottom, setContentInsetBottom] = useState(0);

   // how can I get the height of each children component, sum them up & call setContentInsetBottom(totalHeight) here ?

   return (
   <ScrollView
        automaticallyAdjustContentInsets={false}
        contentInset={{top: 0, bottom: contentInsetBottom}}
        style={styles.scrollView}
        contentContainerStyle={styles.contentContainer}>

        <MySubComponent />
        <Text>{myText}</Text>
        <Image source={{uri: image?.uri}}>
   </ScrollView>)
}
1 Answers

Wrap all content inside the <ScrollView> in a <View>. Then use onLayout to get the height of that parent View.

  const handleScrollContentLayout = (e) => {
    const { height } = e.nativeEvent.layout
    setScrollLayoutHeight(height)
  }

...

<View onLayout={handleScrollContentLayout}>
{ /* scrollView content... */ }
</View>

Then you can use the scrollLayoutHeight as per your needs to set the height at runtime.

Related