Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; }'
like image 402
Jake Chambers Avatar asked Jan 14 '21 18:01

Jake Chambers


People also ask

What is the type of ref in React TypeScript?

createRef() in React With TypeScript. In the class component for getting the reference of the input field, we use the createRef() method, which is used to access any DOM element in a component and returns a mutable ref object.

How do you pass references in TypeScript?

To use refs with functional components use a special useRef hook. It is a generic function, so we can pass a type-parameter, that will tell TypeScript what type is acceptable for this ref. // using `HTMLInputElement` as a type parameter. // to bind the element with the ref.

What is the type of useRef in TypeScript?

useRef can only be null, or the element object. I then put the h1Ref variable inside the ref property of my H1 element. After the first render React. useRef will return an object with a property key called current .

What is the type of React props TypeScript?

React has its own, built-in way of type checking called “prop types”. Together with TypeScript this provides a full, end-to-end type-checking experience: Compiler and run-time.


Video Answer


1 Answers

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>
  );
};
like image 111
cbr Avatar answered Oct 20 '22 15:10

cbr