Eric Hz
Eric Hz

Reputation: 55

ScrollView height adapting to content

I can't seem to manage this simple layout and all the tricks I find for ScrollView don't match my case. My content has a header and a footer that should "stick" to it. But when my content becomes too big, the header should be naturally stuck at the top of the screen, the footer at the bottom of the screen, and the middle part is taken by the content which should be scrollable. Here is the code for the layout and I join some screens.

small  content in  scrollview long content in scrollview

<View style={styles.screen}>
    <View style={styles.contentHeader}>
        {contentHeader}
    </View>
    <ScrollView style={styles.content}>
        {content}
    </ScrollView>
    <View style={styles.contentFooter}>
        {contentFooter}
    </View>
</View>

My problem is that the ScrollView should take only the height required by its content but it does not. Any suggestions ?

Upvotes: 0

Views: 822

Answers (1)

Waheed Akhtar
Waheed Akhtar

Reputation: 3187

You can use FlatList and use its ListFoooterComponent and ListHeaderComponent for rendering your header and footer you can also render these with ScrollView but its recommended to use FlatList for more performant and support.

Have a look at this to FlatList

https://reactnative.dev/docs/flatlist

Otherwise, you can use stickyHeaderIndices prop for rendering header in ScollView and place your footer outside of the ScrollView with these styles.

This will work

<View style={styles.screen}>
    <ScrollView style={styles.content} stickyHeaderIndices={[0]}>
       <View style={styles.contentHeader}>
            {contentHeader}
       </View>
       {content}
    </ScrollView>
    <View style={[styles.contentFooter, {position: 'absolute, bottom: 0}]}>
        {contentFooter}
    </View>
</View>

Upvotes: 1

Related Questions