React Native: detecting element approaching center of screen

Viewed 73

Basically I want to implement a scrollspy - I have a categorized list of items scrolled vertically inside the <ScrollView>, which also has a nested <ScrollView> with items scrolled horizontally (image example below).

const DetailsScreen = ({ route }) => {
    const horizontalListRef = React.useRef();
    const categories = route.params.categories;
    const itemsList = route.params.list;

    return (
        // Vertically scrolled view
        <ScrollView
            // This gives me the vertical offset of the scrolled view
            onScroll={({ nativeEvent }) => console.log(nativeEvent.contentOffset.y)}
        >
            <View>
                <Text>Screen Title</Text>
                // Horizontally scrolled view
                <ScrollView ref={horizontalListRef} horizontal={true}>
                    {categories.map((category) => (
                        <View
                            key={category.id}
                            onLayout={({ nativeEvent }) => /* This gives me the position of the element */}
                        ><Text>{category.name}</Text></View>
                    ))}
                </ScrollView>
            </View>
            {
                itemsList.map((list) => (
                    <View
                        key={list.id}
                        onLayout={({ nativeEvent }) => /* This gives me the position of categorized list */
                    >
                        <Text>{list.category}</Text>
                        list.items.map((item) => (
                            <View key={item.id}>
                                <Text>{item.name}</Text>
                            </View>
                        )
                    </View>
                ))
            }
        </ScrollView>
    );
}

How do I detect when the vertical list's <Text>{list.category}</Text> is approaching the middle of the screen so I could highlight and scroll to the corresponding category in the horizontal list as shown on the image below?

enter image description here

0 Answers
Related