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; }'
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.
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.
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 .
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.
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>
);
};
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