I have a TypeScript React video component which I want to play on click. I'm hoping to do this by using a click handler which accesses the video by ref and calls .play(), however I'm getting this error:
TS2339: Property 'play' does not exist on type 'RefObject<HTMLVideoElement>'.
Here's my code (with irrelevant parts omitted):
class FullBleedVideo extends React.Component<PropDef, StateDef> {
private fullBleedVideo: React.RefObject<HTMLVideoElement>;
constructor(props: PropDef) {
super(props);
this.fullBleedVideo = React.createRef();
this.state = {
isPlaying: false,
};
}
public handleVideoClick() {
this.setState({ isPlaying: true });
this.fullBleedVideo.play();
}
render() {
const { isPlaying } = this.state;
return (
<div className="video_container" onClick={this.handleVideoClick.bind(this)}>
<video
ref={this.fullBleedVideo}
>
<source src={src} type="video/mp4" />
</video>
</div>
);
}
}
I'm quite new to TypeScript, but not sure where I've gone wrong?
To play video in React, you need to use the HTML video element, specify a source of the video and its type. Along with these required attributes, you can provide additional properties to customize the video player.
We create a React ref by calling React.createRef and assign it to a ref variable. We pass our ref down to <FancyButton ref={ref}> by specifying it as a JSX attribute. React passes the ref to the (props, ref) => ... function inside forwardRef as a second argument.
useRef: The useRef is a hook that uses the same ref throughout. It saves its value between re-renders in a functional component and doesn't create a new instance of the ref for every re-render. It persists the existing ref between re-renders. createRef: The createRef is a function that creates a new ref every time.
this.fullBleedVideo.current.play();
will work. You can access DOM via current
property.
https://reactjs.org/docs/refs-and-the-dom.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With