Search code examples
react-nativescrollview

How to set dynamic height to a view inside a scrollView in reactNative


This is my code:

<ScrollView>
  <View>
   <Text1/> 
   <Text2/>
   ... 
  </View>

The ScrollView only works when the View inside has a specific height, but the number of objects inside the view can change, so the height should adjust accordingly. However, I don't know how to do it.

I attempted to calculate the height by multiplying the height of a single text object by the number of objects (they all have the same height), but it seems that the height is not sufficient to activate the ScrollView.


Solution

  • A way to achieve this behavior is by using the flexGrow property in React Native.

    Here is an example using views with dynamic sizes. I added borders and colors for easier visualization.

     <ScrollView
        contentContainerStyle={{
          flexGrow: 1,
          borderColor: "green",
          borderWidth: 5
        }}
      >
        <View style={{ borderColor: "purple", borderWidth: 5 }}>
          <Text>Hello</Text>
        </View>
        <View style={{ borderColor: "red", borderWidth: 5 }}>
          <Text style={{ fontSize: 30 }}>World</Text>
        </View>
      </ScrollView>