React Js Detect When Video Finished Playing
React Js Detect When Video Finished Playing:To detect when a video finishes playing in a React.js application, you can use the "onEnded" event provided by the HTML5 video element. Simply attach an event handler function to this event, which will trigger when the video reaches its end.




Thanks for your feedback!
Your contributions will help us to improve service.
How can you detect when a video has finished playing in a Reactjs?
In this React.js code snippet, we have an App component that renders a video element. The key functionality is the onEnded
attribute, which is set to the handleVideoEnd
function. When the video finishes playing, this function is triggered, and it displays an alert saying 'Video has ended'. This allows you to detect when a video has finished playing and perform any desired actions afterward. The video element also has controls and a source (URL) specified.
React Js Detect When Video Finished Playing Example
xxxxxxxxxx
<script type="text/babel">
function App() {
const handleVideoEnd = () => {
// This function will be called when the video ends
// You can perform any actions you want here
alert('Video has ended');
};
return (
<div className='container'>
<h3>React Js Detect When Video Finished Playing </h3>
<video
controls
onEnded={handleVideoEnd}
src="https://www.w3schools.com/tags/movie.mp4"
/>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('app'));
</script>
Output of React Js Detect When Video Finished Playing
How do I auto-restart a video in Reactjs when it finishes playing?
This React.js code snippet creates a functional component called "App" that renders an HTML5 video player. It uses the useRef hook to create a reference to the video element. When the video ends (triggered by the "onEnded" event), the "handleVideoEnd" function is called. This function logs a message and restarts the video by calling "play()" on the video element using the reference. This ensures that when the video finishes playing, it automatically restarts.
React Js Restart Video when it ends
xxxxxxxxxx
<script type="text/babel">
const {useRef} = React;
function App() {
const videoRef = useRef(null);
const handleVideoEnd = () => {
// This function will be called when the video ends
// You can perform any actions you want here
console.log('Video has ended');
// Restart the video when it ends
if (videoRef.current) {
videoRef.current.play();
}
};
return (
<div className='container'>
<h3>React Js Restart Video when it ends</h3>
<video
controls
ref={videoRef}
onEnded={handleVideoEnd}
src="https://www.w3schools.com/tags/movie.mp4"
/>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('app'));
</script>