reactjsreact-hookscarouselswiper.jsreact-player

Pause other videos when slide is changed | Swiper.js | React Player


I need help for my video carousel using Swiper.js and React Player. I want to stop the video when swiped and became inactive slide. I set the state like below and it does behave as I wanted. But now, it autoplays the active slide even autoplay prop is false. How can I achieve both stop playing inactive video and not auto playing the active one? I have stuck here almost 3 weeks so I appreciate any suggestions.

UPDATE: Revised question to be clearer and includes autoplay issue.

 const videodata = [
        {
            id: 0,
            name: 'video1',
            url: 'https://www.youtube.com/1234',
        },
        {
            id: 1,
            name: 'video2',
            url: 'https://www.youtube.com/5678',
        },
    ]


const [isPlaying, setIsPlaying] = useState(false)
 <Swiper             
     onSlideChange={(swiper) => {
     if (swiper.activeIndex !== videodata.id) {
         setIsPlaying(false)} 
                        }}
         autoplay={false}                  
         watchSlidesProgress={true}>
      {videodata.map((data) => (
      <SwiperSlide>
        <ReactPlayer
          key={data.id}
          url={data.url}
          controls={true}
          playing={isPlaying}/>
        </SwiperSlide>
       ))}
 </Swiper>

Solution

  • I finally found a solution. No need to use useContext like [this][1]. This also works with pagination={{clickable: true}} and grabCursor={true} I hope this helps somebody!

    const videodata = [
      {
        id: 1,
        url: "https://www.youtube.com/1234"
      },
      {
        id: 2,
        url: "https://www.youtube.com/1234"
      },
      {
        id: 3,
        url: "https://www.youtube.com/1234"
      }
    ];
    
    export default function App() {
      const [isPlaying, setIsPlaying] = useState(null);
    
      return (
          <Swiper
            className="mySwiper"
            onSlideChange={() => {
              setIsPlaying(null);
            }}
            autoplay={false}
            watchSlidesProgress={true}
          >
            {videos.map((data) => (
              <SwiperSlide key={data.id}>
                <ReactPlayer
                  key={data.id}
                  url={data.url}
                  controls={true}
                  onPlay={() => {
                    setIsPlaying(data.id);
                  }}
                  playing={isPlaying === data.id}
                />
              </SwiperSlide>
            ))}
          </Swiper>
      );
    }
    
    
      [1]: https://stackoverflow.com/questions/66329185/pause-other-video-if-selected-video-is-playing-in-react