Use React components methods on Hooks

Asked

Viewed 282 times

1

Next people, I have a flat list in my React Native app, where in it I need to use a "ref" to access her "scrollToEnd()" method, but how I’m using Hooks I can’t use the ref.

Here’s an example of what I want to do:

export default function Test(){
 return( 
  <FlatList data={data}
   keyExtractor={id => String(id)}
   ref={ref.flatlist}
   onContentSizeChange={ref.flatlist.scrollToEnd()}
   renderItem={(item) => <Text>{item}</Text>
  />
 )
}

remembering that the above code is an example, but it explains more or less what I want to do. Does anyone know how to use that ref on the Hooks or use methods of the React components on the hook without needing these refs? (the scrollToEnd() method I took from the Flatlist documentation)

1 answer

1


To use the ref on functional components you need to use the ref hook (useRef). N React documentation you find an explanation about it: https://pt-br.reactjs.org/docs/hooks-reference.html#useref It works as follows, you declare a variable within the scope of your component, which will receive the return of the hook (a mutable object), then, in the component you want to reference, just pass the variable you just created in the prop "ref" of it. Follow an example with flatlist:

import React, {useRef} from 'react'; // importando o hook
export default function Test(){
const flatListRef = useRef(null); // declarando o hook e inicializando como null
 return( 
  <FlatList 
   ref={flatListRef} // aqui recebemos a ref da flatlist
   data={data}
   keyExtractor={id => String(id)}
   onContentSizeChange={flatListRef.scrollToEnd()} //aqui agora é possível acessar os metodos disponíveis do flatlist
   renderItem={(item) => <Text>{item}</Text>
  />
 )
}

I don’t remember now whether to use Current before the referenced object methods (example: flatListRef.current.scrollToEnd()), do a test. All flatlist methods you can also find in the React Native doc: https://reactnative.dev/docs/flatlist

  • 1

    thank you very much kkkk, I started using with classes even pq the answer was taking dms but I did a test here and it really worked ent if I need elsewhere already know how to do thank you!

  • You’re welcome, good luck!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.