Search code examples
react-nativescrollview

React-Native: Is there anyway to track whether user has read the whole content available on the current page?


I have this usecase where I want to track how much of available content user has read. In the application, there is one scrollView inside which multiple subsections are present which are also scrollable. How can I track the percentage of total content the user has read overall?


Solution

  • You can use this component to get the percentage of the scroll

    import React from 'react';
    import {ScrollView, Text, View} from 'react-native';
    
    const scrollPercentage = ({layoutMeasurement, contentOffset, contentSize}) => {
      return ((layoutMeasurement.height + contentOffset.y)/contentSize.height) * 100;
    };
    
    function PercentageScrollView({onReadPercentageChanged, children}) {
    
      return <ScrollView
        onScroll={({nativeEvent}) => {
          onReadPercentageChanged(scrollPercentage(nativeEvent));
        }}
        scrollEventThrottle={400}
      >
        {children}
      </ScrollView>
    }
    
    export default PercentageScrollView;
    

    Use in your component like this :

    <PercentageScrollView onReadPercentageChanged={(readPercentage)=>{
      setPercentage(readPercentage);
    }}>
      <View>
        ...
      </View>
    </PercentageScrollView>