Detect ScrollView has reached the end

Eldelshell picture Eldelshell · Dec 9, 2016 · Viewed 54.7k times · Source

I have a Text with long text inside a ScrollView and I want to detect when the user has scrolled to the end of the text so I can enable a button.

I've been debugging the event object from the onScroll event but there doesn't seem any value I can use.

Answer

Henrik R picture Henrik R · Dec 9, 2016

I did it like this:

import React from 'react';
import {ScrollView, Text} from 'react-native';

const isCloseToBottom = ({layoutMeasurement, contentOffset, contentSize}) => {
  const paddingToBottom = 20;
  return layoutMeasurement.height + contentOffset.y >=
    contentSize.height - paddingToBottom;
};

const MyCoolScrollViewComponent = ({enableSomeButton}) => (
  <ScrollView
    onScroll={({nativeEvent}) => {
      if (isCloseToBottom(nativeEvent)) {
        enableSomeButton();
      }
    }}
    scrollEventThrottle={400}
  >
    <Text>Here is very long lorem ipsum or something...</Text>
  </ScrollView>
);

export default MyCoolScrollViewComponent;

I wanted to add paddingToBottom because usually it is not needed that ScrollView is scrolled to the bottom till last pixel. But if you want that set paddingToBottom to zero.