2

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>)
}
Leem.fin
  • 40,781
  • 83
  • 202
  • 354

1 Answers1

0

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.

Tom Bombadil
  • 3,455
  • 1
  • 13
  • 24
  • Thanks. It works, however, the content height looks doubled than the actual content overall. I have to `setScrollLayoutHeight(height*0.5)` in order to avoid big empty space at the bottom of the ScrollView content. – Leem.fin Apr 13 '21 at 19:47
  • console.log the height value and check if its changing. Usually, the onLayout gets called more than once and the final value is often the right one. In my case, I was receiving 0 at first render. Therefore, I set the returned height into state with the useState hook to update accordingly. – Tom Bombadil Apr 13 '21 at 19:54
  • https://reactnative.dev/docs/direct-manipulation#measurecallback -> Check out this callback as well. It's another option to get height dynamically. Though, I've not used it before. – Tom Bombadil Apr 13 '21 at 19:56