How can I detect when video finished playing react?

Viewed 7604

Since React uses lifecycle methods and the virtual dom how can I detect when my video has finished playing. I found another question like this on stackoverflow that suggested to use componentWillUnmount but there's no point at which I remove the video from the dom, so componentWillUnmount won't get fired...

How can I detect when video finished playing react?

3 Answers

You could also use the onEnded media event on the video element. This feature has been supported since 2015; it's much easier to work with and can be used in functional components.

const myCallback = () => (console.log('Video has ended'));

<video autoplay onEnded={() => myCallback()}>
    <source src={[yourVideoURL]} type="video/mp4" />
</video>

Also make sure loop is not true on the video element, because then, the onEnded event will never be fired.

More information here: https://reactjs.org/blog/2015/09/10/react-v0.14-rc1.html

Note: It took me a while to figure this out, but onEnded is not triggered the you also have the loop attribute as well. Which make sense, but in my case I needed both. So I ended up removing the loop and start it again in the onEnded function.

Related