Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript React - access video element by ref and call .play()

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?

like image 730
Robkwood Avatar asked Nov 05 '18 21:11

Robkwood


People also ask

How do you play the video in React?

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.

How do you pass a ref to a component?

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.

What is the difference between useRef and createRef?

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.


1 Answers

this.fullBleedVideo.current.play(); will work. You can access DOM via current property.

https://reactjs.org/docs/refs-and-the-dom.html

like image 148
ZeroCho Avatar answered Nov 04 '22 21:11

ZeroCho