1

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.

Nick Morgan
  • 33
  • 1
  • 8
  • have a look at https://stackoverflow.com/questions/30096038/react-native-getting-the-position-of-an-element, this will help you make sure the position of the view – Alen.Toma Jun 29 '21 at 18:21
  • Use [onViewableItemsChanged](https://reactnative.dev/docs/flatlist#onviewableitemschanged) prop in Flatlist to keep track of the Views that are visible and accordingly play/pause videos. – Kartikey Jun 29 '21 at 18:32

1 Answers1

2

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}
/>
Kartikey
  • 4,516
  • 4
  • 15
  • 40