Sercan Samet Savran
Sercan Samet Savran

Reputation: 947

React Native ScrollView scroll to end

Is there a way to automatically scroll down the ScrollView element of react-native on change?

This is something that I was looking for react-native, while developing chat functionality within my app.

There were no sufficient answers though. That's why I'm answering my own questions in hope, that somebody could make use of it.

Upvotes: 5

Views: 10907

Answers (1)

Sercan Samet Savran
Sercan Samet Savran

Reputation: 947

First thing to know is the scrollTo() method of the ScrollView of react-native. The scrollTo() method scrolls the scrollview to a certain position.

The second thing we'll make use of is the onContentSizeChanged() event of the ScrollView.

In addition to that, we have to call our scrollview in our event. Therefore we're using the "useRef" hook to create a reference to our scrollview.

To use the "useRef" hook we've to import it first:

import {useRef} from "react";

create a const as a reference to your scrollview component:

const scrollViewRef = useRef(null);

create a function that handles the onContentSizeChanged() event of the scrollView:

function scrollViewSizeChanged(height){
       // y since we want to scroll vertically, use x and the width-value if you want to scroll horizontally
       scrollViewRef.current?.scrollTo({y: height, animated: true}); 
}

define the scrollview and set the ref and the onContentSizeChange event to the previously created function.

<ScrollView ref={scrollViewRef} onContentSizeChange={(width,height) => {scrollViewSizeChanged(height)}}>
      {/* HERE GOES YOUR CONTENT*/}
</ScrollView>

Tested with react-native version: 6.4.0

EDIT: Found a method, that already scrolls to end.

You can alternatively just define the onContentSizeChanged-event like so:

<ScrollView ref={scrollViewRef} onContentSizeChange={() => {scrollViewRef.current?.scrollToEnd()}}>
        {/* HERE GOES YOUR CONTENT*/
</ScrollView>

For better overview, I just made the call in the line the event is defined and got rid of the additional function.

Upvotes: 15

Related Questions