Nick Morgan
Nick Morgan

Reputation: 33

How do I get the current item displayed in a FlatList?

I'm using a flatlist to render a feed of videos for my project. I want to prevent the videos from auto-playing when they're not visible on the screen. I figured the simplest way to do this would be to see if the current video on the screen is currently visible/active and if so, I can set props to true for playing etc.

I'm having a lot of issues trying to achieve this however an I wanted to know if anyone can give me some pointers as I'm new to React-Native.

Upvotes: 1

Views: 3832

Answers (1)

Kartikey
Kartikey

Reputation: 4992

You can use onViewableItemsChanged prop from FlatList

Docs Here

Working Example of FlatList of Videos with automatic play/pause feature

Something as shown below

const [Viewable, SetViewable] = React.useState([]);
const ref = React.useRef(null);

const onViewRef = React.useRef((viewableItems) => {
  let Check = [];
  for (var i = 0; i < viewableItems.viewableItems.length; i++) {
    Check.push(viewableItems.viewableItems[i].item);
  }
  SetViewable(Check);
});

const viewConfigRef = React.useRef({ viewAreaCoveragePercentThreshold: 80 });

<FlatList
  data={Videos}
  keyExtractor={(item) => item._id.toString()}
  renderItem={({ item }) => <VideoPlayer {...item} viewable={Viewable} />}
  ref={ref}
  onViewableItemsChanged={onViewRef.current}
  viewabilityConfig={viewConfigRef.current}
/>

Upvotes: 2

Related Questions