Search code examples
reactjsreact-nativescrollview

React-Native onScroll Event is Not Being Called


i am trying to create a paginated/infinate scroll component, but the onScroll event is never fired.

does anyone know what i am doing wrong here?

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { ScrollView } from 'react-native';

class PaginatedScrollView extends Component {
    static propTypes = {
        paginationSize: PropTypes.number,
        data: PropTypes.array.isRequired,
        renderItem: PropTypes.func.isRequired
    }

    handleOnScroll (event) {
        console.log(event.nativeEvent.contentOffset.y);
    }

    render () {
        const {
            data,
            renderItem,
            paginationSize
        } = this.props;

        return (
            <ScrollView
                onScroll={e => this.handleOnScroll(e)}
                onContentSizeChange={console.log}
            >
                {data
                    .slice(1, paginationSize)
                    .map(renderItem)
                }

            </ScrollView>
        );
    }
}

export default PaginatedScrollView;

it seems onContentSizeChange is getting called but onScroll does not.


Solution

  • You need to either bind handleOnScroll function in constructor or change it to arrow function

    Bind handleOnScroll in constructor

      constructor(props){
           super(props);
           this.handleOnScroll = this.handleOnScroll.bind(this);
      }
    

    OR

    Change it to arrow function

     handleOnScroll = event => {
        console.log(event.nativeEvent.contentOffset.y);
    }