Search code examples
javascriptarraysfunctionreact-nativereact-native-video

How to prevent map() from render whole array at once in react-native


Hi folks I'm using viewPager and inside viewpager I'm rendering the array of videos using map. But I wan to show 1 video at one time as I'm giving height and width 100%. But when I run the app the all videos start playing.Only one show on the screen and the sound of other videos playing too. I want to prevent that. How can I do that?

Here is my code.

<ViewPager
        onPageSelected={(e) => {
          setActive(e.nativeEvent.position);
          // setPaused(true);
        }}
        orientation="vertical"
        style={{height: '100%'}}
        initialPage={0}>
        {vids.map((item,index) => {
          return (
            <View key={index}>
              <Video
               paused={item.paused}
                source={{uri: item.vid}}
                style={styles.mediaPlayer}
                volume={0.5}
                resizeMode="cover"
                repeat={true}
                
                onReadyForDisplay={() => SetVideoLoad(false)}
              /></ViewPager

Solution

  • You can simply do this in the following way

    const [pause,setPause]= useState(true)
    
                   <Video
                   paused={pause}
                    source={{uri: item.vid}}
                    style={styles.mediaPlayer}
                    volume={0.5}
                    resizeMode="cover"
                    repeat={true}
                    onTouchStart={()=>{setPause(!pause)} //<=== Add this line
                    onReadyForDisplay={() => SetVideoLoad(false)}
                  />
    

    I hope this will help you.Happy Coding :D