Search code examples
react-nativeexporeact-native-flatlist

Getting refs to rendered videos in FlatList


I have an application where I am rendering a video component using expo-video-player via FlatList as this list could grow in the future and I want to keep things optimized as possible.

What I want to accomplish is that when I click to play on one video in the list, all others will pause if they are playing. I'm using all functional components and typically if it wasn't in a FlatList could reference a video with the following:

const videoRef = useRef(null);

...

<Video 
   ref={videoRef}
   ...
/>

and then call videoRef.current.pauseAsync() to pause it somewhere else in my code.

However, now that it is in a FlatList I am having trouble understanding how to link the ref for each video and be able to get the ref back to call pauseAsync() on the previous video that is playing.

Any direction/guidance would be appreciated.


Solution

  • You prob need to create an Array of Refs.

    Something like this:

    const videoRefs = [];
    
    const videos = ['url.com/xyz.mp4', 'url.com/abc.mp4'];
    
    videos.forEach((video, index) => {
      videoRefs.push(useRef(null));
    });
    
    ...
    
    renderItem = ({item, index}) => {
      <Video 
         ref={videoRefs[index]}
         ...
      />
    }