Home > Software engineering >  React Native Expo VirtualizedList how to use scrollToEnd method?
React Native Expo VirtualizedList how to use scrollToEnd method?

Time:03-19

I am trying to use a scrollToEnd() method on VirtualizedList. But interestingly I cannot find any example on the internet explaining how to use methods with VirtualizedList.

I tried to use it like below, but obviously it didn't work

<VirtualizedList
          data={serverData}
          initialNumToRender={4}
          renderItem={renderItem}
          keyExtractor={item => item.id.toString()}
          getItemCount={getItemCount}
          getItem={getItem}
          ListFooterComponent={renderFooter}
          scrollToEnd={{ animated: true }}
        />  

CodePudding user response:

The scrollToEnd function is inherited from ScrollView by VirtualizedList. It is a function, not a prop.

You need to create a reference to the list component and call the function using this reference. This can be done as follows.


const listRef = useRef(null);

<VirtualizedList
    ref= {listRef}
    onContentSizeChange= {()=> listRef.current.scrollToEnd()} 
/> 

The above code scrolls to the end of the list when the content size of its data changes. However, you can call the scrollToEnd function whenever you want to.

CodePudding user response:

VirtualizedListexpose scrollToEnd as method not props. You have to use React Ref to access it.

const listRef = React.useRef(null)

// Scroll to list end - Call this function after add new items to list for example
const scrollToListEnd = ()=> listRef.current?.scrollToEnd({ animated: true })

<VirtualizedList
  data={serverData}
  initialNumToRender={4}
  renderItem={renderItem}
  keyExtractor={(item) => item.id.toString()}
  getItemCount={getItemCount}
  getItem={getItem}
  ListFooterComponent={renderFooter}
  ref={listRef}
/>;


  • Related