Steph
Steph

Reputation: 177

How to scroll to index of clicked list item in FlatList

I have a react native FlatList, and when an item from that list is clicked, I would like the page to scroll to the top of that list item (so the top of the item is now at the top of the page/screen). I have been working with scrollToIndex. I added an onPress to the renderItem, which calls a function "onClickItem". I have put scrollToIndex inside that function and passed in the index of the item being clicked. This is not working though. Where am I going wrong please?

 import React from 'react';
 import { View, FlatList, StyleSheet} from 'react-native';
 import { NavigationEvents } from 'react-navigation';
 import SwipeableCard from './SwipeableCard';

   
  class Tab extends React.Component {

    constructor(props) {
     super(props)

   this.state = {
     currentTab: null,
     records: [],            
     selectedRecords: [],     
     pageOffset: 0,
     pageSize: 10,      
     searchQuery: null,
   }
    this.listRef = null
    this.searchRef = null
  }
    
  renderTabItem = ({ item, index }) => 
   <SwipeableCard    
     onPress={ () => this.onClickItem(item, index)}     
   />

  onClickItem(item, index){
   this.listRef.scrollToIndex({index})              
 }


render() {
  return (
    <>         
    <FlatList 
      ref={ref => this.listRef = ref}
      style={{ paddingTop: 8 }}
      initialNumToRender={this.state.pageSize}
      data={this.state.records}
      onEndReachedThreshold={0}
      onEndReached={this.loadMore}
      keyExtractor={item => item.isNew ? 'new' : item.id}
      renderItem={this.renderTabItem}          
    />      
   </>      
  )
 }

  export default withTheme(Tab);

Upvotes: 0

Views: 1834

Answers (1)

Maxwell
Maxwell

Reputation: 546

What is the behavior you are currently seeing? Is there an error?

First thing I'd ask to see is the SwipeableCard class. It's uncommon to put onPress as a prop there since it would require you to have a prop named onPress in your SwipeableCard class. Rather, you should wrap SwipeableCard with TouchableOpacity or Pressable, and put the onPress function there.

If that's not the case, you'll need to show me a bit more of your code.

Upvotes: 0

Related Questions