function VideoPlayer() {
const videoRef = React.useRef(); // assigning the object returned by a hook to a variable
function handleClick() {
videoRef.current.play(); // calling the required method on the current property of the object
}
return (
<>
<video ref={videoRef} src="./clip.mp4" /> // pointed a ref attribute to the element => got direct access to the DOM element
<button onClick={handleClick}>▶️</button> /* attached a handler to a button */
</>
);
}
// For class components, it's similar, except that the ref is created/declared using the React.createRef() function, and the ref itself is usually written with this
class VideoPlayer extends React.Component {
constructor() {
super();
this.videoRef = React.createRef(); // created a ref and assigned it to a variable - it will be a property of this
}
handleClick = () => {
this.videoRef.current.play(); // similarly, we call the required method on the current field of the object
};
render() {
return (
<>
<video ref={this.videoRef} src="./clip.mp4" /> //
<button onClick={this.handleClick}>▶️</button> //
</>
);
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter