Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 858
Tiago Palmas Avatar asked Mar 06 '20 14:03

Tiago Palmas


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)

like image 117
Will Jenkins Avatar answered Oct 17 '22 10:10

Will Jenkins


const flatListRef = useRef();

    <FlatList
        ref={flatListRef}
        onContentSizeChange={() => flatListRef?.current?.scrollToEnd()} // scroll end
        data={myChats}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item, index }) => <View/>}
    />
like image 3
patel jigar Avatar answered Oct 17 '22 09:10

patel jigar


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

like image 1
Pardeep Sharma Avatar answered Oct 17 '22 09:10

Pardeep Sharma