Tiago Palmas
Tiago Palmas

Reputation: 345

Flatlist scrollToIndex with Hooks useRef

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.

Upvotes: 11

Views: 18772

Answers (2)

Pardeep Sharma
Pardeep Sharma

Reputation: 37

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

Upvotes: 1

Will Jenkins
Will Jenkins

Reputation: 9887

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)

Upvotes: 13

Related Questions