3

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.

0

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.