gabogabans
gabogabans

Reputation: 3553

How can I get visible item index from scrolling position from FlatList in React-Native?

I have a horizontal FlatList where I render a collection, now I want to know which item is into view (index) taking into account that each item width is almost equal to device width, lets say 400, how can I get visible item index on my onScroll method?

<FlatList scrollEventThrottle={16} onScroll={handleScroll} showsHorizontalScrollIndicator={false} style={{ width:'100%', '}} 
        horizontal={true} data={categories} keyExtractor={item => item.toString()}
        renderItem={({ item, index }) => 
            <TouchableOpacity  style={{ width:400,height:275 }}>{ item }</Text> 
            </TouchableOpacity>}
        />  

handleScroll method:

const handleScroll = (event) => {
        console.log(event.nativeEvent.contentOffset.x);
       
      };

Upvotes: 0

Views: 4574

Answers (1)

Babjonii
Babjonii

Reputation: 43

You can use FlatList onViewableItemsChanged prop to get what you want.

  const _onViewableItemsChanged = React.useCallback(({ viewableItems, changed }) => {
    console.log("Visible items are", viewableItems);
    console.log("Changed in this iteration, ", changed);
  }, []);

  const _viewabilityConfig = {
    itemVisiblePercentThreshold: 60
  }
  
  
  
  
   <FlatList
        scrollEventThrottle={16}
        showsHorizontalScrollIndicator={false}
        style={{ width: '100%' }}
        horizontal={true}
        data={categories}
        onViewableItemsChanged={_onViewableItemsChanged}
        viewabilityConfig={_viewabilityConfig}
        keyExtractor={item => item.toString()}
        renderItem={({ item, index }) =>
          <TouchableOpacity style={{ width: 400, height: 275 }}><Text>{item}</Text>
          </TouchableOpacity>}
      />

viewabilityConfig can help you to make whatever you want with viewability settings. In code example 60 means that item is considered visible if it is visible for more than 60 percents.

Upvotes: 1

Related Questions