Sean Tansey
Sean Tansey

Reputation: 459

React Hooks - refs for ScrollView in functional component with hooks?

Im converting a react native project from all class components to functional components with hooks. I have a messaging page with a ScrollView that auto scrolls to the bottom. How do i convert this to work in a functional component? Using ref and this.scrollView cause errors.

<ScrollView 
   ref={ref => this.scrollView = ref}
   onContentSizeChange={(contentWidth, contentHeight)=> {this.scrollView.scrollToEnd({animated: true})}}
>
{...content...}
</ScrollView>

Upvotes: 2

Views: 13091

Answers (2)

Rahul Shakya
Rahul Shakya

Reputation: 1425

const scrollRef = useRef(); in function App()

And in onPress use scrollRef.current?.scrollTo({ y: 0, animated: true, });

Upvotes: 1

Samuel Goldenbaum
Samuel Goldenbaum

Reputation: 18929

In the body of your component:

function App(props) {    
   const scrollViewRef = useRef();
...

On the component:

<ScrollView 
   ref={scrollViewRef}
   onContentSizeChange={(contentWidth, contentHeight)=> {scrollViewRef.current.scrollToEnd({animated: true})}}
>
{...content...}
</ScrollView>

Upvotes: 20

Related Questions