1

I'm working on a simple React Component to play video. It works fine, now I'd like to know when the video stops so that I can hide him and start some other things. I'd like to use 'ended' event, below the code, I but I keep getting: Cannot read property 'addEventListener' of undefined which, as far as I understand, means that the html tag introVideo is null but I don't know what I'm doing wrong.

export default class ShowMovieWindow extends React.Component {

constructor(props) {
    super(props);
    this.handleVideoEnd = this.handleVideoEnd.bind(this);
};

handleVideoEnd() {
    console.log("Finished");
}

componentDidMount() {
    this.refs.introVideo.addEventListener("ended", this.handleVideoEnd);
}

render() {
    return (
        <Dialog isOpen={this.props.isOpen}>
            <div className={Classes.DIALOG_BODY}>
                <div>
                    <video ref="introVideo" autoPlay>
                        <source src={'./asset/video/intro.mp4'} type="video/mp4"/>
                    </video>
                </div>
            </div>
        </Dialog>
    );}}
1
  • Hi NiBE, please try my solution below and let me know if that helps :) Commented Aug 19, 2019 at 9:56

1 Answer 1

2

The video tag has an onEnded event-listener by default which triggers when the video ends. There's no need to create a ref.

See working sandbox: https://codesandbox.io/s/lingering-sun-qvlmz

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

import "./styles.css";

class ShowMovieWindow extends React.Component {
  constructor(props) {
    super(props);
    this.handleVideoEnd = this.handleVideoEnd.bind(this);
  }

  handleVideoEnd() {
    console.log("Finished");
  }

  render() {
    return (
      <div>
        <div>
          <video onEnded={this.handleVideoEnd} controls autoPlay>
            <source
              src="http://techslides.com/demos/sample-videos/small.webm"
              type="video/webm"
            />
          </video>
        </div>
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<ShowMovieWindow />, rootElement);
Sign up to request clarification or add additional context in comments.

1 Comment

haha no worries. You're very welcome and happy coding @NiBE :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.