Big Guy
Big Guy

Reputation: 782

Playing two videos in one Video element React

I want to put a short intro video that plays before every video on my web app. This fiddle: http://jsfiddle.net/bnzqkpza/ has a lot of the functionality I'm looking for, but I am using React so I need to rewrite the jquery so it doesn't change the DOM. I'm new to React, can anyone help me with this?

HTML:

<video src="http://www.w3schools.com/html/mov_bbb.mp4" id="myvideo" width="320" height="240" controls style="background:black">
</video>

JS:

var myvid = document.getElementById('myvideo');
var myvids = [
  "http://www.w3schools.com/html/mov_bbb.mp4", 
  "http://www.w3schools.com/html/movie.mp4"
  ];
var activeVideo = 0;

myvid.addEventListener('ended', function(e) {
  // update the active video index
  activeVideo = (++activeVideo) % myvids.length;

  // update the video source and play
  myvid.src = myvids[activeVideo];
  myvid.play();
});

Upvotes: 1

Views: 5552

Answers (2)

Max
Max

Reputation: 1567

Edited to use React 16 example.

You can try something like this:

const urls = [
  "https://www.w3schools.com/html/mov_bbb.mp4", 
  "https://www.w3schools.com/html/movie.mp4"
];

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      currentUrlIdx: 0,
    }

    this.handleEnded = this.handleEnded.bind(this);
  }

  handleEnded(e) {
    const nextUrlIdx = (this.state.currentUrlIdx + 1) % urls.length
    this.setState({ currentUrlIdx: nextUrlIdx });
  }

  render() {
    return <div>
      <video src={urls[this.state.currentUrlIdx]} autoPlay onEnded={this.handleEnded}/>
    </div>;
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

https://codepen.io/anon/pen/OOxmjJ?editors=0010

Upvotes: 0

Hoyen
Hoyen

Reputation: 2519

I created a sample in CodeSandbox. The Video component would look something like this:

import React from "react";
import ReactDOM from "react-dom";

export default class Video extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      index: 0,
      src: this.props.videos[0]
    };
  }

  componentDidMount() {
    let video = ReactDOM.findDOMNode(this);
    video.addEventListener("ended", e => {
      if (this.state.index < this.props.videos.length - 1) {
        let nextIndex = this.state.index + 1;
        this.setState({
          index: nextIndex,
          src: this.props.videos[nextIndex]
        });
      }
    });
    video.play();
  }
  componentDidUpdate(prevProps, prevState) {
    let video = ReactDOM.findDOMNode(this);
    video.play();
  }
  render() {
    return (
      <video
        src={this.state.src}
        controls
        autplay="true"
        playsinline
        muted
        crossorigin
      />
    );
  }
}

The code sandbox url: https://codesandbox.io/s/n7p9yvp260

Upvotes: 1

Related Questions