I have a flatlist showing videos. I want that when a video goes out of the view it should be paused. I am maintaining the pause state in each of the Posts
component.
class Posts extends React.PureComponent {
constructor() {
super()
this.state = {
pause: true,
}
return(){
<Video
pause={this.state.pause}
//other props
/>
}
}
I am using react-native-video
.
I have tried using onViewableItemsChanged
prop of Flatlist
but it doesn't change the state.
I tried this . But it doesn't seem to work for me.
How should I proceed ?
I finally did this using redux. Not sure whether it is the right way.
Home.js
Posts.js
Whenever the
viewableItemsChanged
is trigger I am adding the changed posts id in an array and calling the action with the array of post ids. In thePosts
component I am checking if the post ids match, if so I am setting the pause state to true.Here is a possible solution using react-native-inviewport. This dependency is only a single index file that contains a component that has a callback when view is in the viewport. It could easily be modified to suit your needs.
I have constructed a very simple app that has a FlatList. The 11th item in the FlatList is a video. That should mean that the video is off the screen when the App renders so the viddeo won't be playing, once the video comes fully into the viewport it should then start playing.
App.js
VideoPlayer.js
This is a component that contains the Video component. The video is wrapped in the
InViewPort
component that has a callback function. The callback returns true when the component it surrounds is completely in the viewport and false when it is not fully in the viewport. The callback callsthis.handlePlaying
which in turn calls eitherthis.playVideo
orthis.pauseVideo
depending on the boolean value.Here is a snack showing it working https://snack.expo.io/@andypandy/video-only-playing-when-in-viewport
I should point out that if the video is not fully in the viewport then it will not play. I am sure some tweaking could be done to
react-native-inviewport
so that it would play the video if it was partially in the viewport if that is what you wanted, perhaps by passing the height of the video to theInViewPort
component.here is how i simply did the trick inside my card component that have video
both currentIndex and currentVisibleIndex are passed the component from the FlatList parent
my FlatList pass the renderItem index as currentIndex
finally my this is how to calculate currentVisibleIndex please make sure to read viewabilityConfig
please let me know if this is helpful