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
Here is the simplest solution I could muster:
<ListView
ref={ref => (this.listView = ref)}
onLayout={event => {
this.listViewHeight = event.nativeEvent.layout.height;
}}
onContentSizeChange={() => {
this.listView.scrollTo({
y: this.listView.getMetrics().contentLength - this.listViewHeight
});
}}
/>;
Use onContentSizeChange to keep track of the bottom Y of the scroll view (height)
https://facebook.github.io/react-native/docs/scrollview.html#oncontentsizechange
var _scrollToBottomY
<ScrollView
onContentSizeChange={(contentWidth, contentHeight)=>{
_scrollToBottomY = contentHeight;
}}>
</ScrollView>
then use the ref name of the scroll view like
this.refs.scrollView.scrollTo(_scrollToBottomY);
For React Native 0.41 and later, you can do this with the built-in scrollToEnd method:
<ScrollView
ref={ref => {this.scrollView = ref}}
onContentSizeChange={() => this.scrollView.scrollToEnd({animated: true})}>
</ScrollView>
In case anyone in 2020 or later is wondering how to achieve this with functional components. This is how I did:
ref={ref => scrollView = ref }
onContentSizeChange={() => scrollView.scrollToEnd({ animated: true })}>
A bit late... but look at this question. Scroll to top of ScrollView
ScrollView has a "scrollTo" method.
If you use TypeScript You need to do this
interface Props extends TextInputProps {
scrollRef?: any;
}
export class Input extends React.Component<Props, any> {
scrollRef;
constructor(props) {
this.scrollRef = React.createRef();
}
<ScrollView
ref={ref => (this.scrollRef = ref)}
onContentSizeChange={() => {
this.scrollRef.scrollToEnd();
}}
>
</ScrollView>