willmahon
willmahon

Reputation: 339

How do you use a FlatList inside a ScrollView in react native

I'm trying to use a flatlist to to display posts from a database, but the flatlist is only taking half the screen and the other 2 containers are taking up roughly half the screen as well, currently when I scroll on the flatlist, the posts are just being displayed in the bottom half of the screen (as expected), but I want the whole page to scroll, so the posts can be seen on a full screen so they're easier to read.

Here is a simplified version of my layout...

<View>
  <View>
    // some content
  </View>
  <View>
    // some content
  </View>
  <FlatList
    // posts displayed from a database
  />
</View>

Is there a way to keep the Flatlist component but allow the whole screen to slide up when first scrolling until the FlatList reaches the top of the page, and then it starts scrolling through the FlatList?

Upvotes: 5

Views: 4013

Answers (2)

Graham
Graham

Reputation: 39

Your current simplified layout:

<View>
    <View>
        // some content
    </View>
    <View>
        // some content
    </View>
    <FlatList
      // posts displayed from a database
    />
</View>

To allow the entire screen, not just the FlatList, to scroll you can use the ListHeaderComponent property:

<View>
    <FlatList
        ListHeaderComponent={
            <View>
                // some content
            </View>
            <View>
                // some content
            </View>        
        }
      // other FlatList properties to render your posts 
    />
</View>

And as you may expect, you can also render components underneath the list of posts using the ListFooterComponent:

<View>
    <FlatList
        ListHeaderComponent={
            <View>
                // some header content
            </View>
        }
        ListFooterComponent={
            <View>
                // some footer content
            </View>        
        }
      // other FlatList properties to render your posts 
    />
</View>

Upvotes: 1

Naresh
Naresh

Reputation: 1251

You shouldn't render FlatList inside a ScrollView because of the performance issue. what you can do is define a FlatList as the main container in your component and then pass all other views that you want to display above FlatList to the ListHeaderComponent prop of FlatList

  <FlatList
    ListHeaderComponent={
      <View>
        // some content
      </View>
      <View>
        // some content
      </View>
    }
    data={someDataArray}
    renderItem={({ item }) => (
        <SomeItem />
    )}
    keyExtractor={(data) => data.id}
  />

This way your whole screen would be scrollable

Upvotes: 9

Related Questions