mukul
mukul

Reputation: 181

How to play 2 videos one after the other in ReactJS?

I want to play intro video just once followed by another video which loops. I have this code to detect when first video ends but how do i load the second video and set it to play in loop?

const vidIndex = 0;
const videos = [videoIntro, videoLoop];
return (
    <div className="main">
        <video src = {videos[vidIndex]} autoPlay muted onEnded={() => vidIndex++} />
    </div>
);

Thanks.

Upvotes: 1

Views: 2257

Answers (1)

Asplund
Asplund

Reputation: 2486

You can simply use a useState to track the video index. CodeSandbox

import { useEffect, useState, useRef } from "react";

const videoIntro = "https://www.w3schools.com/tags/movie.mp4";
const videoLoop =
  "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4";

function App() {
  const [vidIndex, setVidIndex] = useState(0);
  const ref = useRef(null);
  useEffect(() => {
    if (vidIndex === 0 && ref.current) {
      ref.current.play();
    }
  }, [ref, vidIndex]);
  return (
    <div className="main">
      <video
        style={{ display: vidIndex === 1 ? "none" : "block" }}
        src={videoIntro}
        autoPlay
        muted
        onEnded={() => setVidIndex((idx) => idx + 1)}
      />
      <video
        style={{ display: vidIndex === 0 ? "none" : "block" }}
        src={videoLoop}
        muted
        loop
        ref={ref}
      />
    </div>
  );
}

Upvotes: 4

Related Questions