Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 622
Kevvv Avatar asked Dec 08 '25 08:12

Kevvv


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

like image 165
Tim Avatar answered Dec 10 '25 00:12

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!