For a chat-like app, I want to keep a ScrollView
component scrolled to the bottom, because newest messages appear under the older ones. Can we adjust the scroll
I had a similar problem, but after reading this page (which give me a headache!) I find this very nice npm package which just invert the ListView and make everything easy for a chat application!!
This answers your question: https://stackoverflow.com/a/39563100/1917250
You need to keep constantly scrolling to the bottom of the page by calculating the height of the content minus the height of its scrollView.
For anyone writing function component that can use hook,
import React, { useRef } from 'react';
import { ScrollView } from 'react-native';
const ScreenComponent = (props) => {
const scrollViewRef = useRef();
return (
<ScrollView
ref={scrollViewRef}
onContentSizeChange={() => scrollViewRef.current.scrollToEnd({ animated: true })}
/>
);
};
You can invert the scroll/list view using the react-native-invertible-scroll-view module, then simply call ref.scrollTo(0)
to scroll to bottom.
Install the module:
npm install --save react-native-invertible-scroll-view
Then import the component:
import InvertibleScrollView from 'react-native-invertible-scroll-view';
Then use the following JSX instead of a ScrollView
:
<InvertibleScrollView inverted
ref={ref => { this.scrollView = ref; }}
onContentSizeChange={() => {
this.scrollView.scrollTo({y: 0, animated: true});
}}
>
{ /* content */ }
</InvertibleScrollView>
This works because react-native-invertible-scroll-view
flips the entire view's content. Note that the view's children will also render in the opposite order to a normal view - the first child will appear at the bottom.