Dan
Dan

Reputation: 29375

ScrollView not respecting flex rules

This results in a screen that is half blue and half yellow, should it not be 2/3 yellow?

    <View style={{flex:1,flexDirection:'column'}}>
       <View style={{flex:1,backgroundColor: 'blue'}}></View>
       <ScrollView style={{flex:2}} contentContainerStyle={{flex:1,backgroundColor: 'yellow'}}></ScrollView>
    </View>

Upvotes: 0

Views: 126

Answers (1)

Tim
Tim

Reputation: 10719

In general you are right, but react native's ScrollView behaves a little bit differently. As you can read in the docs:

Keep in mind that ScrollViews must have a bounded height in order to work, since they contain unbounded-height children into a bounded container (via a scroll interaction). In order to bound the height of a ScrollView, either set the height of the view directly (discouraged) or make sure all parent views have bounded height. Forgetting to transfer {flex: 1} down the view stack can lead to errors here, which the element inspector makes easy to debug.

In order to achieve your wanted behavior, you can do the following:

<View style={{flex:1,flexDirection:'column'}}>
       <View style={{flex:1,backgroundColor: 'blue'}}></View>
       <View style={{flex:2}}> // surround scrollview with flex 2 
        <ScrollView contentContainerStyle={{flex:1,backgroundColor: 'yellow'}}></ScrollView>
       </View>
</View>

Upvotes: 2

Related Questions