JAVASCRIPT
Programmatic Media Control with useRef Hook
Learn to programmatically control HTML5 media elements like `<video>` or `<audio>` in React using the `useRef` hook. This snippet demonstrates playing, pausing, and resetting a video.
import React, { useRef, useState } from 'react';
function VideoPlayer() {
const videoRef = useRef(null);
const [isPlaying, setIsPlaying] = useState(false);
const handlePlayPause = () => {
if (videoRef.current) {
if (isPlaying) {
videoRef.current.pause();
} else {
videoRef.current.play();
}
setIsPlaying(!isPlaying);
}
};
const handleReset = () => {
if (videoRef.current) {
videoRef.current.pause();
videoRef.current.currentTime = 0;
setIsPlaying(false);
}
};
const handleEnded = () => {
setIsPlaying(false);
};
return (
<div>
<h2>Video Player Control</h2>
<video
ref={videoRef}
width="640"
height="360"
controls={false} // Disable default controls to use custom ones
onEnded={handleEnded}
style={{ border: '1px solid #ccc' }}
>
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4" />
Your browser does not support the video tag.
</video>
<div>
<button onClick={handlePlayPause}>
{isPlaying ? 'Pause' : 'Play'}
</button>
<button onClick={handleReset} style={{ marginLeft: '10px' }}>
Reset
</button>
</div>
<p>Using <code>useRef</code> to interact directly with the video DOM element.</p>
</div>
);
}
export default VideoPlayer;
How it works: This snippet illustrates how `useRef` can be used to directly interact with DOM elements in React. A `videoRef` is created and attached to the `<video>` element. This allows direct access to the video element's properties and methods (like `play()`, `pause()`, `currentTime`) without requiring a re-render. This is particularly useful for media controls or any scenario where you need to imperatively manage a DOM node.