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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With