Search code examples
react-nativereact-native-listviewreact-native-scrollview

How to determine whether scrollview (or listview) child is mostly in view in React Native


I am currently using a ListView to display some data. Due to the design, the rows take up about 70% of the height of the screen which means there is always at least 2 rows visible, with a max of three. What I would like to determine is which row is mostly visible.

I am currently using onChangeVisibleRows, but that just tells me which rows are visible or have entered or left the view.

Any ideas?


Solution

  • This will only work when you know there are 2-3 (no more, no less) rows visible at a time:

    onChangeVisibleRows={(visibleRows) => {
        const visibleRowNumbers = Object.keys(visibleRows.s1).map((row) => parseInt(row));
        if (visibleRowNumbers.length === 2) {
            // visible row is visibleRowNumbers[0]
        }
        if (visibleRowNumbers.length === 3) {
            // visible row is visibleRowNumbers[1]
        }
    }
    

    Caveat being that it doesn't perfectly map to the row that is most visible is considered visible. However, in using it, it makes sense while scrolling. In my particular application, there is a visible shift between the active and inactive rows so it helps the user understand whats happened.