Cannot access the scrollToIndex() method in React Native using the useRef hook

Viewed 1940

I'm trying to access the scrollToIndex() method or scrollToItem() method from FlatList using the useRef hook in a functional component. I want to be able to use flatListRef.current.ScrollToIndex() in my component, similar to the way a class-based component uses this.flatListRef.ScrollToIndex():

 const flatListRef = useRef(React.createRef)
 <FlatList 
    data={items}
    renderItem={({ item }) => <Item item={item} />}
    keyExtractor={item => item.id.toString()}
    contentContainerStyle={styles.card}
    horizontal={true}
    showsHorizontalScrollIndicator={false}  
    ref={flatListRef}                      
/>

console.logging flatListRef.current doesn't show the aforementioned methods I'm looking for.

1 Answers

You don't need to create a ref with createRef, you can just use useRef(). Another important thing is to use scrollToIndex correctly. See documentation and the code below.

Code:

const CustomFlatList = () => {
  const flatListRef = useRef(); // useRef 
  return (
    <View>
    <FlatList 
        data={items}
        renderItem={({ item }) => <Text style={{width: 100}}> {item.id} </Text> }
        keyExtractor={item => item.id.toString()}
        contentContainerStyle={styles.card}
        horizontal={true}
        showsHorizontalScrollIndicator={false}  
        ref={flatListRef} // create ref                
    />
     <TouchableHighlight onPress={() => flatListRef.current.scrollToIndex({index: 4, animated: true })}>
     <Text> ScrollToIndex </Text>
      </TouchableHighlight>
    </View>
  )
}

Working Example:

https://snack.expo.io/B1rfdbsuS

Related