Flatlist scrollToIndex with Hooks useRef

Viewed 12705

Im trying to scroll to the middle of my data in flatlist using React Hooks and the method scrollToIndex but i cant make reference to it. I achieved that with class using something like ref={component => (this.list = component)} but i can reached with useRef.

const refContainer = useRef(null); 

useEffect(()=>{   
        if(refContainer){
            refContainer.scrollToIndex({ animated: true, index: 0 });

        }    
    },[status])

<FlatList
                ref={()=>refContainer}
                refreshing={loading}
                onRefresh={() => console.log('refreshing')}
                keyExtractor={(item, index) => item.date}
                showsVerticalScrollIndicator={false}
                style={{flex: 1,}}
                data={kits}    
                onEndThreshold={0}
                renderItem={({item, index}) => renderItem(item, index)}   

            />

shows me the error: refContainer.scrollToINdex is not a function.

3 Answers

To access the ref of the current render, you need to use .current - so in your case, use refContainer.current:

useEffect(()=>{   
        if(refContainer.current){
            refContainer.current.scrollToIndex({ animated: true, index: 0 });

        }    
    },[status])

Also, set up your ref like this:

<FlatList ref={refContainer} ...

(See the docs for more info on .current)

const flatListRef = useRef();

    <FlatList
        ref={flatListRef}
        onContentSizeChange={() => flatListRef?.current?.scrollToEnd()} // scroll end
        data={myChats}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item, index }) => <View/>}
    />

Step 1 : Create ref for flatlist , for example see below ,

     let myList = useRef();

Step 2 : Then add ref to your flatlist component like this

    <FlatList
    data = {data}
    ref={myList}
    renderItem = {YourComponent}
    initialScrollIndex={0}
    horizontal = {true}
    showsHorizontalScrollIndicator={false}
   />

Step 3 Then scroll the flatlist on any button click or any event like below

   myList.current.scrollToIndex({animated:true,index:0,viewPosition:0});

Thanks! Hope it helps

Related