10

I'm trying to control the play/pause state of a video using ref's in React.js, my code works but there are tslint errors I am trying to work through:

function App() {
    const playVideo = (event:any) => {
        video.current.play()
    }
    const video = useRef(null)

    return (
        <div className="App">
            <video ref={video1} loop src={bike}/>
        </div>
    );
}

This will cause

TS2531: Object is possibly 'null'.

So I try to change const video = useRef(null) to const video = useRef(new HTMLVideoElement())

and I get: TypeError: Illegal constructor

I have also tried: const video = useRef(HTMLVideoElement) which results in:

TS2339: Property 'play' does not exist on type '{ new (): HTMLVideoElement; prototype: HTMLVideoElement; }'
Jake Chambers
  • 513
  • 2
  • 6
  • 22
  • It's a ` – Mike 'Pomax' Kamermans Jan 14 '21 at 18:28
  • 1
    @Mike'Pomax'Kamermans [`useRef`](https://reactjs.org/docs/hooks-reference.html#useref) is the hook version of `createRef`. – cbr Jan 14 '21 at 18:36
  • ref={video1} should be ref={video} – Dev Null Aug 02 '22 at 22:50

1 Answers1

14

To set the type for the ref, you set the type like this: useRef<HTMLVideoElement>(). Then, to handle the fact that the object is possibly null (since it's null or undefined before the component is mounted!), you can just check whether it exists.

const App = () => {
  const video = useRef<HTMLVideoElement>();
  const playVideo = (event: any) => {
    video.current && video.current.play();
  };

  return (
    <div className="App">
      <video ref={video} loop src={bike} />
    </div>
  );
};
cbr
  • 12,563
  • 3
  • 38
  • 63
  • I saw this `useRef(null!)` syntax in Twilio's sample react app, and just could not figure out this syntax. I've never seen this before, and couldn't find it in the React documentation. Do you have a source with more information about it? Thanks – Panpaper Mar 21 '21 at 23:43
  • 2
    @Panpaper [`useRef`](https://reactjs.org/docs/hooks-reference.html#useref) is a React hook. `useRef(null)` initializes its value with null. `useRef(null)` is TypeScript which tells the compiler that the value stored inside the ref is of type `HTMLVideoElement`. The `<>` are related to [generics](https://www.typescriptlang.org/docs/handbook/2/generics.html). The exclamation mark is called the [non-null assertion operator](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator). – cbr Mar 21 '21 at 23:51
  • 1
    @Panpaper Not sure if the ! is needed there. Could depend on your TypeScript version and tsconfig settings. – cbr Mar 21 '21 at 23:54