How can I define the type for a <video> reference in React using Typescript?
Asked Answered
S

1

11

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; }'
Schweiker answered 14/1, 2021 at 18:26 Comment(3)
It's a <video> element. Don't use the src attribute, use <source> elements. Also, if this is actual React, use createRef to create a ref.Berke
@Mike'Pomax'Kamermans useRef is the hook version of createRef.Bergson
ref={video1} should be ref={video}Televisor
B
16

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>
  );
};
Bergson answered 14/1, 2021 at 18:35 Comment(3)
I saw this useRef<HTMLVideoElement>(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? ThanksGenniegennifer
@Genniegennifer useRef is a React hook. useRef(null) initializes its value with null. useRef<HTMLVideoElement>(null) is TypeScript which tells the compiler that the value stored inside the ref is of type HTMLVideoElement. The <> are related to generics. The exclamation mark is called the non-null assertion operator.Bergson
@Genniegennifer Not sure if the ! is needed there. Could depend on your TypeScript version and tsconfig settings.Bergson

© 2022 - 2024 — McMap. All rights reserved.